在SQL中的循环中执行动态查询

时间:2016-02-19 13:16:38

标签: sql sql-server parallel-data-warehouse

我正在尝试在SQL / PDW中的while循环内执行动态查询。此查询将为我提供最大/最小日期以及事实表中日期的不同计数。我需要为我的数据库中的所有模式执行此操作(所有模式都具有相同的表结构)。我试图执行的查询如下:

DECLARE @intCNT INT
SET @intCNT = 1
DECLARE @strSQL1 VARCHAR(1000)
DECLARE @strSQL2 VARCHAR(1000)
DECLARE @strSQL3 VARCHAR(100)


SET @strSQL1 = 'SELECT MAX(FT_DT) AS MAX_DT, 
                    MIN(FT_DT) AS MIN_DT,  
                    COUNT(DISTINCT FT_DT) AS DT_CNT 
                FROM '

SET @strSQL2 = CONCAT('(SELECT TABLE_SCHEMA
                        FROM 
                            (SELECT ROW_NUMBER() OVER(ORDER BY TABLE_SCHEMA) AS ROW_NUM, 
                                TABLE_SCHEMA
                            FROM INFORMATION_SCHEMA.TABLES
                            WHERE TABLE_NAME = ''FT_TBL''
                                AND TABLE_SCHEMA LIKE ''F%'')T
                        WHERE ROW_NUM = ',@intCNT,')' )

SET @strSQL3 = '.FT_TBL'

EXEC (@strSQL1 + @strSQL2 + @strSQL3)

执行此操作时,出现以下错误:

Msg 102, Level 15, State 1, Line 11
Incorrect syntax near '.'.

是否与语法有关?我想在我的PDW实例上使用它。我也试过SQL Server,但得到了同样的错误

2 个答案:

答案 0 :(得分:1)

您的代码可以用带有以下查询的游标替换,以便您可以为每个架构选择

DECLARE @Schema_Name VarChar

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT DISTINCT TABLE_SCHEMA
FROM TABLE_SCHEMA
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'FT_TBL'
AND TABLE_SCHEMA LIKE 'F%'

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @Schema_Name 
WHILE @@FETCH_STATUS = 0
BEGIN 
    --Do something with Id here
    execute CONCAT(CONCAT('SELECT MAX(FT_DT) AS MAX_DT, 
                MIN(FT_DT) AS MIN_DT,  
                COUNT(DISTINCT FT_DT) AS DT_CNT 
            FROM ',@Schema_Name),'FT_TBL')
    FETCH NEXT FROM MY_CURSOR INTO @Schema_Name
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

答案 1 :(得分:0)

你真正想要的是:

SELECT MAX(FT_DT) AS MAX_DT, 
                    MIN(FT_DT) AS MIN_DT,  
                    COUNT(DISTINCT FT_DT) AS DT_CNT 
                FROM 
(SELECT TABLE_SCHEMA
                        FROM 
                            (SELECT ROW_NUMBER() OVER(ORDER BY TABLE_SCHEMA) AS ROW_NUM, 
                                TABLE_SCHEMA
                            FROM INFORMATION_SCHEMA.TABLES
                            WHERE TABLE_NAME = 'FT_TBL'
                                AND TABLE_SCHEMA LIKE 'F%')T
                        WHERE ROW_NUM = 1)
.FT_TBL

来自@ strSQL3的.FT_TBL会破坏您的查询。也许它应该是

set @strSQL3 = ' FT_TBL'