1

我有以下代码适用于一张桌子,但我试图弄清楚如何让它循环。

DECLARE @sql NVARCHAR(2000) 
DECLARE @table VARCHAR(100) 
DECLARE @command NVARCHAR(1000) 

SELECT @table = ( VV.SRC_CD ) 
FROM   VV 

SET @sql = 'SELECT [CD],[SRC_CD],[SRC_CD_DESC],[DSC],[REFRESH_DT],[GEN_DSC] = CAST(null as VARCHAR(50))      INTO dbo.vv_' + @table 
           + 
' FROM [vv] A WHERE A.SRC_CD <> ''GEN''      AND A.DSC <> ''NO DATA'' AND A.DSC <> ''(BLANK) NO'' AND A.src_cd = ''' 
           + @table + '''' 

EXEC Sp_executesql 
  @stmt = @sql

填充@table 变量的代码返回一行。我想要做的是让这个过程为该行的表中每个不同的值循环一次。distinct 子句在这里不起作用,我尝试了一个基本的表数组,但没有运气。

我需要修改它以使用游标吗?

4

1 回答 1

0

听起来您需要一个光标,例如:

DECLARE @Iterator NVARCHAR(100)
       ,@sql NVARCHAR(MAX)
DECLARE xyz CURSOR
FOR
--Select stuff to iterate over
SELECT DISTINCT SRC_CD
FROM w

OPEN xyz 
FETCH NEXT FROM xyz 
INTO @Iterator 

WHILE @@FETCH_STATUS = 0
BEGIN

--Do stuff
SET @sql = 'SELECT [CD],[SRC_CD],[SRC_CD_DESC],[DSC],[REFRESH_DT],[GEN_DSC] = CAST(null as VARCHAR(50)) 
            INTO dbo.vv_' + @Iterator +' 
            FROM [vv] A 
            WHERE A.SRC_CD <> ''GEN'' 
                 AND A.DSC <> ''NO DATA'' 
                 AND A.DSC <> ''(BLANK) NO'' 
                 AND A.src_cd = ''' + @Iterator + ''''
PRINT (@sql)    

    FETCH NEXT FROM xyz 
    INTO @Iterator 
END

CLOSE xyz 
DEALLOCATE xyz 
GO

PRINT留在那里,这样您就可以在执行之前确保输出符合要求。

于 2013-08-26T20:12:27.997 回答