我有几年前为了类似目的而构建的这个脚本,尽管它带有文本字段。它找到符合条件的列,然后在这些列中搜索值。由于您的范围是不确定的,因此您可能无法比这样的事情做得更好。
您可能需要稍微调整一下以包含 uniqueidentifier 列 - 如果这实际上是数据类型 - 或者使用 equal 而不是 like 搜索。
如果这是你要定期重用的东西,你可以给它提供一个常用表或列的列表来找到这些东西,所以找到东西不需要很长时间。
/*This script will find any text value in the database*/
/*Output will be directed to the Messages window. Don't forget to look there!!!*/
SET NOCOUNT ON
DECLARE @valuetosearchfor varchar(128), @objectOwner varchar(64)
SET @valuetosearchfor = '%putYourGuidHere%' --should be formatted as a like search
SET @objectOwner = 'dbo'
DECLARE @potentialcolumns TABLE (id int IDENTITY, sql varchar(4000))
INSERT INTO @potentialcolumns (sql)
SELECT
('if exists (select 1 from [' +
[tabs].[table_schema] + '].[' +
[tabs].[table_name] +
'] (NOLOCK) where [' +
[cols].[column_name] +
'] like ''' + @valuetosearchfor + ''' ) print ''SELECT * FROM [' +
[tabs].[table_schema] + '].[' +
[tabs].[table_name] +
'] (NOLOCK) WHERE [' +
[cols].[column_name] +
'] LIKE ''''' + @valuetosearchfor + '''''' +
'''') as 'sql'
FROM information_schema.columns cols
INNER JOIN information_schema.tables tabs
ON cols.TABLE_CATALOG = tabs.TABLE_CATALOG
AND cols.TABLE_SCHEMA = tabs.TABLE_SCHEMA
AND cols.TABLE_NAME = tabs.TABLE_NAME
WHERE cols.data_type IN ('char', 'varchar', 'nvchar', 'nvarchar','text','ntext')
AND tabs.table_schema = @objectOwner
AND tabs.TABLE_TYPE = 'BASE TABLE'
AND (cols.CHARACTER_MAXIMUM_LENGTH >= (LEN(@valueToSearchFor) - 2) OR cols.CHARACTER_MAXIMUM_LENGTH = -1)
ORDER BY tabs.table_catalog, tabs.table_name, cols.ordinal_position
DECLARE @count int
SET @count = (SELECT MAX(id) FROM @potentialcolumns)
PRINT 'Found ' + CAST(@count as varchar) + ' potential columns.'
PRINT 'Beginning scan...'
PRINT ''
PRINT 'These columns contain the values being searched for...'
PRINT ''
DECLARE @iterator int, @sql varchar(4000)
SET @iterator = 1
WHILE @iterator <= (SELECT Max(id) FROM @potentialcolumns)
BEGIN
SET @sql = (SELECT [sql] FROM @potentialcolumns where [id] = @iterator)
IF (@sql IS NOT NULL) and (RTRIM(LTRIM(@sql)) <> '')
BEGIN
--SELECT @sql --use when checking sql output
EXEC (@sql)
END
SET @iterator = @iterator + 1
END
PRINT ''
PRINT 'Scan completed'
如果这看起来很奇怪,脚本正在执行这样的语句
if exists (select 1 from [schema].[table_name] (NOLOCK)
where [column_name] LIKE '%yourValue%')
begin
print select * from [schema].[table_name] (NOLOCK)
where [column_name] LIKE '%yourValue%'
end
...并且只是在循环中替换[schema]
, [table_name]
, [column_name]
and 。%yourValue%
它的过滤...
- 特定模式中的表(可以删除过滤器)
- 只有表格,没有视图(可以调整)
- 仅包含搜索值的列
(n)char
//(n)varchar
数据(n)text
类型(添加或更改,了解数据类型转换)
最后,输出不会进入结果网格。检查消息窗口(您会看到“受影响的 N 行”)