DECLARE table_cursor CURSOR FOR SELECT t.name AS TableName, c.name AS ColumnName FROM sys.tables t JOIN sys.columns c ON t.object_id = c.object_id WHERE c.system_type_id IN (56, 127) -- 56 表示整数数据类型,127 表示大整数数据类型
OPEN table_cursor FETCH NEXT FROM table_cursor INTO @TableName, @ColumnName
WHILE @@FETCH_STATUS = 0 BEGIN SET @Sql = N'INSERT INTO #Results (TableName, ColumnName) SELECT N''' + @TableName + ''', N''' + @ColumnName + ''' FROM ' + QUOTENAME(@TableName) + ' WHERE ' + QUOTENAME(@ColumnName) + ' = ' + CAST(@SearchValue AS NVARCHAR)
EXEC sp_executesql @Sql
FETCH NEXT FROM table_cursor INTO @TableName, @ColumnName END
DECLARE table_cursor CURSOR FOR SELECT t.name AS TableName, c.name AS ColumnName FROM sys.tables t JOIN sys.columns c ON t.object_id = c.object_id WHERE c.system_type_id IN (167, 175, 231) -- 字符串数据类型的类型码
OPEN table_cursor FETCH NEXT FROM table_cursor INTO @TableName, @ColumnName
WHILE @@FETCH_STATUS = 0 BEGIN SET @Sql = N'INSERT INTO #Results (TableName, ColumnName) SELECT N''' + @TableName + ''', N''' + @ColumnName + ''' FROM ' + QUOTENAME(@TableName) + ' WHERE ' + QUOTENAME(@ColumnName) + ' LIKE ''%' + @SearchValue + '%'''
EXEC sp_executesql @Sql
FETCH NEXT FROM table_cursor INTO @TableName, @ColumnName END