使用UNION t-sql进行Mssql循环

时间:2013-10-17 12:49:19

标签: sql sql-server loops

我只是使用在这个站点Using loop with UNION t-sql给出的Mssql程序来构建我自己的循环过程。
当我执行此代码时:

SELECT      '[hpsdb].[dbo].[' + r.CAMP_TABLE_NAME + ']' 
FROM        [hpsdb].[dbo].[T_HPS_CAMPAIGN_TASK] t
LEFT JOIN   [hpsdb].[dbo].[T_HPS_CAMPAIGN_TABLE_REF] r ON (r.CAMPAIGN_ID=t.CAMPAIGN_ID)
WHERE       SKILL_ID = 2

它返回两个表名。但是当我执行这个程序时,它永远不会结束。

DECLARE @TableName VARCHAR(100)
DECLARE @DSQL VARCHAR(4000)
SET @DSQL = ''

DECLARE cTableList CURSOR FOR
SELECT      '[hpsdb].[dbo].[' + r.CAMP_TABLE_NAME + ']' 
FROM        [hpsdb].[dbo].[T_HPS_CAMPAIGN_TASK] t
LEFT JOIN   [hpsdb].[dbo].[T_HPS_CAMPAIGN_TABLE_REF] r ON (r.CAMPAIGN_ID=t.CAMPAIGN_ID)
WHERE       SKILL_ID = 2

OPEN cTableList

FETCH NEXT FROM cTableList INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @DSQL = @DSQL + 'SELECT ID FROM ' + @TableName + ' UNION ALL '
END

CLOSE cTableList
DEALLOCATE cTableList

-- Remove the last UNION ALL
IF LEN(@DSQL) > 11 SET @DSQL = LEFT(@DSQL,LEN(@DSQL) - 11)

EXEC (@DSQL)

1 个答案:

答案 0 :(得分:1)

你的WHILE LOOP中需要另一个FETCH NEXT语句来继续移动光标,否则你只会留在第一条记录上,而@@FETCH_STATUS的值永远不会改变。

FETCH NEXT FROM cTableList INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
    IF @DSQL = ''
      SET @DSQL = 'SELECT ID FROM [' + @TableName + ']'
    ELSE
      SET @DSQL = @DSQL + ' UNION ALL SELECT ID FROM [' + @TableName + ']'
    FETCH NEXT FROM cTableList INTO @TableName
END