我有一张表#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),
set @sql=
'DECLARE @I INT,
@ROWS INT,
@fym varchar(6)
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)
UPDATE mastercount
SET SCCount = (SELECT count(*)
FROM dw_extract.dbo.dw_fsa_'+cast(@fym as varchar(6))+'
)
WHERE row=@I
set @I=@I+1
end'
exec (@sql)
以上查询提供错误:Must declare the scalar variable "@fym".
答案 0 :(得分:1)
你可以让UPDATE
动态:
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(*) '
SET @sql += ' dw_extract.dbo.dw_fsa_' + cast(@fym as varchar(6))+ ') WHERE row=' + @I
EXEC (@sql)
SET @I=@I+1
END
答案 1 :(得分:0)
这是使用计数表而不是循环执行此操作的另一种方法。如果你的循环真的只有三个,这将不会产生很大的不同。但是如果迭代次数增加,这将对性能产生巨大影响。
DECLARE @sql VARCHAR(max) = '';
WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E2
)
select @sql = @sql + 'UPDATE mastercount set SCCount = (select count(*) from dw_extract.dbo.dw_fsa_'
+ (SELECT RIGHT(FISCAL_YEAR_MONTH,6) from #MONTHS where month_id = t.N)
+ ') WHERE row = ' + CAST(t.N as varchar(6)) + ';'
from cteTally t
where t.N < (SELECT count(*) from #MONTHS)
exec sp_executesql @sql