--定义参数
DECLARE @TYPE NVARCHAR(50) SET @TYPE = 'varchar'
DECLARE @Express NVARCHAR(50) SET @Express = 'like ''%chao.ma%'''
--定义游标->表+栏位
DECLARE MY_CURSOR CURSOR FOR
SELECT t.[name] AS [table],c.[name] AS [column]
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.system_type_id = TYPE_ID(@TYPE) AND t.[name] LIKE '%User%'
ORDER BY t.[name] ,c.[name]
DECLARE @table NVARCHAR(50) , @column NVARCHAR(50)
DECLARE @sql NVARCHAR(max)
DECLARE @sql2 NVARCHAR(max)
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @table,@column
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql='SELECT * FROM ['+@table +'] WHERE [' + @column+'] '+@Express
SET @sql2='IF EXISTS('+@sql+')'+' PRINT '''+REPLACE(@sql,'''','''''') + ''' '
EXEC SP_EXECUTESQL @sql2
FETCH NEXT FROM MY_CURSOR INTO @table,@column
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
DECLARE @TYPE NVARCHAR(50) SET @TYPE = 'varchar'
DECLARE @Express NVARCHAR(50) SET @Express = 'like ''%chao.ma%'''
--定义游标->表+栏位
DECLARE MY_CURSOR CURSOR FOR
SELECT t.[name] AS [table],c.[name] AS [column]
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.system_type_id = TYPE_ID(@TYPE) AND t.[name] LIKE '%User%'
ORDER BY t.[name] ,c.[name]
DECLARE @table NVARCHAR(50) , @column NVARCHAR(50)
DECLARE @sql NVARCHAR(max)
DECLARE @sql2 NVARCHAR(max)
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @table,@column
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql='SELECT * FROM ['+@table +'] WHERE [' + @column+'] '+@Express
SET @sql2='IF EXISTS('+@sql+')'+' PRINT '''+REPLACE(@sql,'''','''''') + ''' '
EXEC SP_EXECUTESQL @sql2
FETCH NEXT FROM MY_CURSOR INTO @table,@column
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
显示结果,可看到有记录的sql语句组合:
SELECT * FROM [User] WHERE [AD] like '%chao.ma%'
SELECT * FROM [UserBatchImport] WHERE [AD] like '%chao.ma%'