动态查询变量错误

时间:2015-12-08 04:06:19

标签: sql-server sql-server-2008

我有一张表#months,如下所示

MONTH_ID    FISCAL_YEAR_MONTH   MIN_DATE    MAX_DATE
1               FSA201510       20151001    20151031
2               FSA201511       20151101    20151130
3               FSA201512       20151201    20151204

我使用下面的动态查询来更新表SCCount中的列mastercount(有3行) -

DECLARE @sql VARCHAR(8000), @fym varchar(6)

DECLARE @I INT, @ROWS INT

SET @ROWS=(SELECT count(*) from #MONTHS)      
SET @I=1    

WHILE @I<=@ROWS          
BEGIN
    SET @fym=(SELECT RIGHT(FISCAL_YEAR_MONTH,6) from #MONTHS where month_id=@I)

    SET @sql = 'UPDATE mastercount'
    SET @sql += ' SET SCCount = (SELECT count(*) from '
    SET @sql += ' dw_extract.dbo.dw_fsa_' + cast(@fym as varchar(6))+ ') WHERE row=@I'

    EXEC (@sql)

    SET @I=@I+1
END

这会导致错误Must declare the scalar variable "@I". 为什么会这样?

2 个答案:

答案 0 :(得分:0)

这是因为您的动态查询无法识别@I。您应该参数化@I并使用sp_executesql来运行查询:

DECLARE @sql NVARCHAR(8000), @fym VARCHAR(6)

DECLARE @I INT, @ROWS INT

SET @ROWS = (SELECT COUNT(*) FROM #MONTHS)      
SET @I = 1    

WHILE @I <= @ROWS          
BEGIN
    SET @fym = (SELECT RIGHT(FISCAL_YEAR_MONTH,6) FROM #MONTHS WHERE month_id = @I)

    SET @sql = N'UPDATE mastercount'
    SET @sql += N' SET SCCount = (SELECT count(*) from '
    SET @sql += N' dw_extract.dbo.dw_fsa_' + cast(@fym as varchar(6))+ N') WHERE row=@I'

    EXEC sp_executesql @sql, N'@I INT', @I

    SET @I = @I + 1
END

答案 1 :(得分:0)

您需要更改此

 SET @sql += ' dw_extract.dbo.dw_fsa_' + cast(@fym as varchar(6))+ ') WHERE row=@I'

到这个

 SET @sql += ' dw_extract.dbo.dw_fsa_' + cast(@fym as varchar(6))+ ') WHERE row=' + CAST(@I AS NVARCHAR(10))