0

我正在尝试在 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 中尝试过,但得到了同样的错误

4

2 回答 2

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
于 2016-02-19T15:22:23.093 回答
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'
于 2016-02-19T13:21:41.640 回答