Sql-Server
在數據庫中查找特定單詞
目標
在數據庫中的表中找到特定的單詞,並在列表中顯示表和列的名稱。
問題
有太多表無法在數據庫中定位特定單詞。
資訊
- 使用 SQL Server 2012
- 每個表都使用“schemaname.tablename”
這不會很快(在我的本地 AdventureWorks 副本中生成 0 個結果需要一分鐘多的時間)。
DECLARE @SpecificWord NVARCHAR(32); SET @SpecificWord = N'donut'; DECLARE @sql NVARCHAR(MAX); SET @sql = N'SELECT NULL,NULL WHERE 1 = 0'; SET @SpecificWord = N'%' + @SpecificWord + N'%'; SELECT @sql += N' UNION ALL SELECT ''' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) + ''',''' + QUOTENAME(c.name) + ''' WHERE EXISTS ( SELECT 1 FROM ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) + N' WHERE ' + QUOTENAME(c.name) + N' LIKE @s )' FROM sys.columns AS c INNER JOIN sys.tables AS t ON c.[object_id] = t.[object_id] INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] WHERE c.system_type_id IN (35,99,167,175,231,239); EXEC sys.sp_executesql @sql, N'@s NVARCHAR(32)', @SpecificWord;
如果您出於某種原因需要支持
sql_variant
(我建議不要這樣做),則只需要進行一些更改:DECLARE @SpecificWord NVARCHAR(32); SET @SpecificWord = N'donut'; DECLARE @sql NVARCHAR(MAX); SET @sql = N'SELECT NULL,NULL WHERE 1 = 0'; SET @SpecificWord = N'%' + @SpecificWord + N'%'; SELECT @sql += N' UNION ALL SELECT ''' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) + ''',''' + QUOTENAME(c.name) + ''' WHERE EXISTS (SELECT 1 FROM ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) + N' WHERE CONVERT( NVARCHAR(MAX), ' + QUOTENAME(c.name) + N') LIKE @s)' FROM sys.columns AS c INNER JOIN sys.tables AS t ON c.[object_id] = t.[object_id] INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] WHERE c.system_type_id IN (35,98,99,167,175,231,239); EXEC sys.sp_executesql @sql, N'@s NVARCHAR(32)', @SpecificWord;