如何将打印变量保存到SQL Server中的另一个变量中?

时间:2010-08-02 05:04:58

标签: sql-server

这是我从网上抓取的脚本

declare @col varchar(255), @cmd varchar(max)
DECLARE getinfo cursor for 
    SELECT c.name 
    FROM sys.tables t JOIN sys.columns c 
        ON t.Object_ID = c.Object_ID 
    WHERE t.Name = 'tblDeductions' 
    AND c.name like 'fld%name' OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0 
    BEGIN 
        SELECT @cmd = 'IF EXISTS (SELECT top 1 * FROM tblDeductions WHERE [' 
            + @col + '] IS NOT NULL) BEGIN print ''
          ' + @col + ''' end' exec (@cmd)
        FETCH NEXT FROM getinfo into @col
END CLOSE getinfo
DEALLOCATE getinfo

上述查询将显示空值的列名。但是我需要用逗号分隔值将它们保存到另一个变量中。

提前致谢。

1 个答案:

答案 0 :(得分:1)

这应该有效,尽管几乎可以肯定这是一种更有效的方法来做你想要做的事情。

IF OBJECT_ID('tempdb..#t') IS NOT NULL
    DROP TABLE #t

CREATE TABLE #t
(columnName VARCHAR(255))

DECLARE @col VARCHAR(255), @cmd VARCHAR(MAX)
DECLARE getinfo CURSOR FOR 
    SELECT c.name 
    FROM sys.tables t JOIN sys.columns c 
        ON t.Object_ID = c.Object_ID 
    WHERE t.Name = 'tblDeductions' 
    AND c.name LIKE 'fld%name' OPEN getinfo
FETCH NEXT FROM getinfo INTO @col
WHILE @@FETCH_STATUS = 0 
    BEGIN 
        SELECT @cmd = 'IF EXISTS (SELECT top 1 * FROM tblDeductions WHERE [' 
            + @col + '] IS NOT NULL) BEGIN INSERT #t VALUES (''' + @col + ''') end' 
          EXEC (@cmd)
        FETCH NEXT FROM getinfo INTO @col
END CLOSE getinfo
DEALLOCATE getinfo

DECLARE @columnsWithNull VARCHAR(MAX)
SET @columnsWithNull = (SELECT columnName + ','
                       FROM #t FOR  XML PATH(''))

SET @columnsWithNull = LEFT(@columnsWithNull,LEN(@columnsWithNull) - 1)

SELECT @columnsWithNull