SELECT INTO语句不能包含将值分配给变量的SELECT语句

时间:2019-07-17 10:03:03

标签: sql sql-server

我试图创建一个存储过程或函数来查找表中每一列中的空值数量。

我在确定用于将代码转换为存储过程/函数的语法时遇到问题。

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = (
    SELECT '
    ' +
    STUFF((
        SELECT ', [' + c.name + '] = ' + CASE WHEN c.is_nullable = 0 THEN '0' ELSE 'COUNT(*) - COUNT([' + c.name + '])' END
        FROM sys.columns c
        WHERE c.[object_id] = o.[object_id]
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, 'SELECT ''' + SCHEMA_NAME(o.[schema_id]) + '.' + o.name + ''', COUNT(*), ') + '
    FROM [' + SCHEMA_NAME(o.[schema_id]) + '].[' + o.name + ']'
    FROM sys.objects o
    WHERE o.[type] = 'U'
        AND o.is_ms_shipped = 0
        AND [name] = 'BSEG'
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
INTO xzy
PRINT @SQL
EXEC sys.sp_executesql @SQL

我想将结果存储在表中。但是我收到以下错误消息:

Msg 194, Level 15, State 1, Line 2
A SELECT INTO statement cannot contain a SELECT statement that assigns values to a variable.

所以我的最终目标是要有一个存储过程/函数,该存储过程/函数在执行时将在表的每一列中提供空值数量,并将结果存储在另一个结果表中。

2 个答案:

答案 0 :(得分:0)

请您检查以下更改-

从查询中删除分配部分,只需将简单的select语句用作-

SELECT '' +
STUFF((
...

--Note: Write the SQL in such way so that only SQL 
--text from STUFF functions is returned. There is no 
--requirement of assigning the text first to variable @SQL

在INTO键之前添加INSERT,如下所示-

...
INSERT INTO xzy
...

如果仍然不走运,请提供PRINT @SQL命令的输出,并进行上述两项更改。

答案 1 :(得分:-1)

“ INTO xyz”应该位于“ FROM sys.objects o”上方吗?

编辑 试试这个

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = (
    SELECT '
    ' +
    STUFF((
        SELECT ', ' + CASE WHEN c.is_nullable = 0 THEN '0' ELSE 'COUNT(*) - COUNT([' + c.name + '])' END + ' AS [' + c.name + ']'
        FROM sys.columns c
        WHERE c.[object_id] = o.[object_id]
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, 'SELECT ''' + SCHEMA_NAME(o.[schema_id]) + '.' + o.name + ''' as TableName, COUNT(*) as Cnt, ') + '
    INTO xzy
    FROM [' + SCHEMA_NAME(o.[schema_id]) + '].[' + o.name + ']'
    FROM sys.objects o
    WHERE o.[type] = 'U'
        AND o.is_ms_shipped = 0
        AND [name] = 'BSEG' 
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
PRINT @SQL
EXEC sys.sp_executesql @SQL