我在第3列中有一个动态创建的SQL count(*)语句,其中表名是动态元素。我想将第3列中的SQL结果放入第4列中。如何做到这一点?
;with cteTables
as(
SELECT c.name AS 'ColumnName'
,t.name AS 'TableName'
,statmnt = 'select count(*) cnt from '+t.name+' where sq = 0'
,Totals = 0
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'SQ'
), cteTots
as
(
select ColumnName, TableName, statmnt
,Totals2 = '' --<---------------------
from cteTables
)
select * from cteTots
答案 0 :(得分:0)
我认为这是您想要的:
DECLARE @Sql nvarchar(4000);
SELECT @Sql = 'SELECT '+ t.name + ' AS TableName, '+ c.name +' AS ColumnName,
(SELECT COUNT(*) FROM '+ t.name +' WHERE '+ c.name +' = 0) As Total
FROM '+ t.name
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'SQ'
EXEC(@SQL)