SQL Server

时间:2016-10-06 12:36:04

标签: sql-server variables cursor subquery

我有一个SQL命令:

CREATE TABLE #TEMP_TABLE
    ( BUSINESS_DATE DATE
    , COLUMN_NAME VARCHAR(100)
    , ROW_COUNT INT
    , TEST_TIME DATETIME)
DECLARE @COLUMN VARCHAR(MAX)
DECLARE @TABLE_NAME TABLE 
( 
    TABLE_NAME VARCHAR(MAX) 
)
INSERT INTO @TABLE_NAME
SELECT * FROM DATA.DBO.[SOURCE_TABLE]
DECLARE @DATE VARCHAR(8) = '20160429'

DECLARE CURSOR_TB CURSOR FOR
    SELECT TABLE_NAME FROM @TABLE_NAME
OPEN CURSOR_TB
FETCH NEXT FROM CURSOR_TB INTO @TABLE_NAME
WHILE @@FETCH_STATUS = 0
BEGIN  
DECLARE CURSOR_CL CURSOR FOR
        SELECT DISTINCT COLUMN_NAME
        FROM DATA.INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME IN (SELECT TABLE_NAME FROM @TABLE_NAME )
        ORDER BY COLUMN_NAME
    OPEN CURSOR_CL
    FETCH NEXT FROM CURSOR_CL INTO @COLUMN
    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC('
            INSERT INTO #TEMP_TABLE

            SELECT BUSINESS_DATE
                , '''+@COLUMN+''' 
                , COUNT('+@COLUMN+') AS ['+@COLUMN+']
                , SYSDATETIME ()
            FROM DATA.DBO.'+@TABLE_NAME+'
            WHERE BUSINESS_DATE = '''+@DATE+'''
                AND '+@COLUMN+' IS NOT NULL
            GROUP BY BUSINESS_DATE
        ')
        FETCH NEXT FROM CURSOR_CL INTO @COLUMN
    END
    CLOSE CURSOR_CL
    DEALLOCATE CURSOR_CL
    FETCH NEXT FROM CURSOR_TB INTO @TABLE_NAME
END
CLOSE CURSOR_TB
DEALLOCATE CURSOR_TB

SELECT * FROM #TEMP_TABLE

运行此代码后,我遇到了错误:

  

消息137,级别16,状态1,行19必须声明标量变量   " @ TABLE_NAME&#34 ;. Msg 137,Level 16,State 1,Line 38必须声明   标量变量" @ TABLE_NAME"。 Msg 137,Level 16,State 1,Line 47   必须声明标量变量" @ TABLE_NAME"。

你可以帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

您应该使用[@TABLE_NAME]。

Here is the documentation.