INSERT INTO WITH Common Table 表达式 - SQL 服务器

INSERT INTO WITH Common Table Expression - SQL Server

我已经想出如何使用通用 Table 表达式递归查找向某个经理报告的所有员工(感谢 Whosebug!)。

这是适合我的代码:

WITH MyCTE AS 
(
    SELECT [WWID] FROM [x500]..[WorkerPublicExtended] 
    WHERE [MgrWWID] = '10624529' AND ([StatCode] = 'A') AND ([BadgeType] = 'BB') 
    UNION ALL 
    SELECT [WorkerPublicExtended].[WWID] FROM [x500]..[WorkerPublicExtended] 
        INNER JOIN MyCTE ON [WorkerPublicExtended].[MgrWWID] = MyCTE.WWID 
    WHERE [WorkerPublicExtended].[MgrWWID] IS NOT NULL 
        AND ([BadgeType] = 'BB') AND ([StatCode] = 'A')
) 

SELECT *, 'MGR+10624529' AS [source] FROM MyCTE

这非常有效。但是,如果我尝试将其插入另一个 table(这是最终目标),我将找不到不引发一个或多个错误的此代码的任何语法变体。有人可以帮我把这些放在一起吗?

INSERT INTO [LTDtraining].[dbo].[pop00001]
WITH MyCTE AS 
(
    SELECT [WWID] FROM [x500]..[WorkerPublicExtended] 
    WHERE [MgrWWID] = '10624529' AND ([StatCode] = 'A') AND ([BadgeType] = 'BB') 
    UNION ALL 
    SELECT [WorkerPublicExtended].[WWID] FROM [x500]..[WorkerPublicExtended] 
        INNER JOIN MyCTE ON [WorkerPublicExtended].[MgrWWID] = MyCTE.WWID 
    WHERE [WorkerPublicExtended].[MgrWWID] IS NOT NULL 
        AND ([BadgeType] = 'BB') AND ([StatCode] = 'A')
) 

SELECT *, 'MGR+10624529' AS [source] FROM MyCTE

它抛出如下错误:

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

或者一直流行的

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'WITH'.

Msg 319, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

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

如果我插入建议的分号,它会响应

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

所以这让我觉得我不知道自己在做什么,SQL。

可以通过将 INSERT 语句向下移动到 WITH 下方来轻松修复错误,如下所示:

WITH MyCTE AS 
(
    SELECT [WWID] FROM [x500]..[WorkerPublicExtended] 
    WHERE [MgrWWID] = '10624529' AND ([StatCode] = 'A') AND ([BadgeType] = 'BB') 
    UNION ALL 
    SELECT [WorkerPublicExtended].[WWID] FROM [x500]..[WorkerPublicExtended] 
        INNER JOIN MyCTE ON [WorkerPublicExtended].[MgrWWID] = MyCTE.WWID 
    WHERE [WorkerPublicExtended].[MgrWWID] IS NOT NULL 
        AND ([BadgeType] = 'BB') AND ([StatCode] = 'A')
)

INSERT INTO [LTDtraining].[dbo].[pop00001] 
SELECT *, 'MGR+10624529' AS [source] FROM MyCTE