我试图对动态sql游标中的列名进行计数(*(,但出现以下错误:
Warning: Null value is eliminated by an aggregate or other SET operation.
查看上一篇文章了解更多信息:上一篇SO文章
动态sql在这里:
SET @sql = N'
-- Variables
DECLARE @MyTable VARCHAR(50)
DECLARE @ColName VARCHAR(50)
DECLARE @MyColCount INT = 0
SET @MyTable = ''' + @myTableNameFromDynamicSQL + '''
DECLARE TheCur CURSOR
FOR SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID(@MyTable)
AND name <> N''MyID'';
OPEN TheCur
FETCH NEXT FROM TheCur INTO @ColName
WHILE @@FETCH_STATUS = 0
IF @ColName <> N''MyID''
BEGIN
IF @ColName = ''AColumnInQuestion''
BEGIN
SET @MyColCount = (SELECT count(*) as MyColCount FROM ' + @myTableNameFromDynamicSQL + ')
PRINT @MyColCount
PRINT @ColName
END
...'
您所指的特定错误不是错误。这是一个警告,在大多数情况下可以安全地忽略。
尽管如此,似乎(尽管还不清楚(您正在尝试获取表中每列中的Null数。如果是这样的话,你就大错特错了
您不需要游标,而且您的动态SQL完全错误(大多数应该在动态部分之外(,并且还缺少转义/引用。相反,下面的脚本将为您提供每个可为null的列中的null数。它使用STRING_AGG
在所有列上同时生成。
DECLARE @schema sysname = 'dbo';
DECLARE @table sysname = 'YourTable';
DECLARE @sql nvarchar(max) = N'
SELECT ' + (
SELECT STRING_AGG('
COUNT(*) - COUNT(' + QUOTENAME(c.name) + ') AS ' + QUOTENAME(c.name), ','
)
FROM sys.columns c
JOIN sys.tables t ON t.object_id = c.object_id
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.name = @table
AND s.name = @schema
AND c.name <> N'MyID'
AND c.is_nullable = 1
) + '
FROM ' + QUOTENAME(@schema) + '.' + QUOTENAME(@table);
PRINT @sql; -- your friend
EXEC sp_executesql @sql;
db<gt;小提琴