以下脚本运行良好:
DECLARE @SelectClause VARCHAR(100) = 'SELECT id_contato'
,@Query VARCHAR(8000) = ''
SELECT @Query = @Query + @SelectClause + ' FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE '%zumbi' or TABLE_NAME like '%engajado%')
SELECT @Query = LEFT(@Query, LEN(@Query) - LEN(' UNION ALL '))
EXEC (@Query)
但我需要第二列带有表名,以确定信息的来源。
我该怎么做?
答案 0 :(得分:2)
您正在使用查询中已有的table_name
字段,只需将其添加到SELECT
并正确引用,以便它以字符串文字形式返回:
DECLARE @SelectClause VARCHAR(100) = 'SELECT id_contato'
,@Query VARCHAR(8000) = ''
SELECT @Query = @Query + @SelectClause + ','''+Table_Name+''' AS Table_Name FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_NAME LIKE '%zumbi' or TABLE_NAME like '%engajado%')
SELECT @Query = LEFT(@Query, LEN(@Query) - LEN(' UNION ALL '))
EXEC (@Query)
更新了引号,适用于SQL Server。