SQL 查询数据库中包含指定字符串的相关表和相关记录

时间:2022-04-18 13:47:51

记录一下,以后备用;查询结果第一张表为包含字符串的相关表数据,第二章为表名,以此类推

/*
	查询数据库中包含指定字符串的数据表名及相应记录
*/
USE [数据库]
GO

DECLARE @key VARCHAR(30)
SET @key = '查找的内容'    --替换为要查找的字符串
DECLARE @tabName VARCHAR(40),@colName VARCHAR(40)
DECLARE @sql VARCHAR(2000)
DECLARE @tsql VARCHAR(8000)

DECLARE tabCursor CURSOR FOR
SELECT name FROM sysobjects WHERE xtype = 'u' AND name <> 'dtproperties'
OPEN tabCursor
FETCH NEXT FROM tabCursor INTO @tabName
WHILE @@fetch_status = 0
BEGIN
	SET @tsql = ''
	DECLARE colCursor CURSOR FOR 
	SELECT Name FROM SysColumns WHERE id=Object_Id(@tabName) and xtype=167
	OPEN colCursor
	FETCH NEXT FROM colCursor INTO @colName
	WHILE @@fetch_status = 0
	BEGIN
		SET @sql = 'if(exists(select * from ' + @tabName + ' where '
		SET @sql = @sql + @colName + ' like ''%' + @key + '%'')) begin  select * from '
		SET @sql = @sql + @tabName + ' where ' + @colName + ' like ''%' + @key + '%'';select '''
		+ @tabName + ''' as TableName  end'
		SET @tsql = @tsql + @sql + ';'
		
		FETCH NEXT FROM colCursor INTO @colName
	END
	EXEC(@tsql)
	CLOSE colCursor
	DEALLOCATE colCursor
	
	FETCH NEXT FROM tabCursor INTO @tabName
END
CLOSE tabCursor
DEALLOCATE tabCursor