如何循环表创建

时间:2013-08-26 19:59:18

标签: sql sql-server

我有以下代码适用于一个表,但我试图弄清楚如何使它循环。

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子句在这里不起作用,我尝试了一个没有运气的基本表数组。

我是否需要修改它以使用光标?

1 个答案:

答案 0 :(得分: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留在那里,以便在执行之前确保输出符合要求。