我想每次使用一个不同的列执行相同的查询几次并打印列名。
换句话说,我想执行以下内容:
第一次查询
SELECT DISTINCT [Name],[C12],'C12' AS [Description]
FROM #MyTable
第二次查询
SELECT DISTINCT [Name],[C13],'C13' AS [Description]
FROM #MyTable
第三次查询
SELECT DISTINCT [Name],[C14],'C14' AS [Description]
FROM #MyTable
我从现在开始做的是以下代码:
DECLARE @Member AS VARCHAR(20)
DECLARE Csr cursor for SELECT 'C12' UNION SELECT 'C13' UNION SELECT 'C14'
OPEN Csr
FETCH NEXT FROM Csr INTO @Member
WHILE (@@fetch_status <> -1)
BEGIN
exec('SELECT DISTINCT [Name],'+@Member+', ''+@Member+'' AS [Description]
FROM #MyTable
')
FETCH NEXT FROM Csr INTO @Member
END
CLOSE Csr
DEALLOCATE Csr
接近于所需的结果,而是我得到的Description
列
+ @会员+
而不是每次迭代分配给变量的值。
有人可以帮帮我吗?
答案 0 :(得分:1)
不需要游标,可以使用动态SQL轻松完成:
declare @query nvarchar(400) = ''
select @query = @query + ' select name,''' + name + ''',' + name + ' from #MyTable' from tempdb.sys.columns
where object_id = (
select object_id from tempdb.sys.tables
where name like '#MyTable%'
) and name <> 'name'
execute sp_executesql @query