0

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

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)
4

1 回答 1

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
于 2013-10-17T13:44:02.090 回答