我只是使用这个站点上给出的 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)