循环搜索结果集的列名

时间:2019-05-23 08:12:53

标签: sql-server

我正在使用以下查询来返回属于数据库表中名称为%%的所有列名称

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'name%'

现在,我想遍历t.name的结果集并执行类似的操作

Select * from t.name where c.name like 'abc%'

我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果我理解您的问题,则需要生成并执行动态语句:

-- Declarations
DECLARE @stm nvarchar(max) = N''

-- Dynamic statement
SELECT @stm = 
    @stm + CONCAT(
            N'SELECT * FROM ', 
            QUOTENAME(t.name), 
            N' WHERE ',
            QUOTENAME(c.name),
            N' LIKE ''abc%'';'
    )
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'name%'

-- Print and execute statement
PRINT @stm
EXEC sp_executesql @stm