我已经想出如何递归查找使用公用表表达式报告特定经理的所有员工(感谢StackOverflow!)。
这是适用于我的代码:
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
这完美无缺。但是,如果我尝试将其插入到另一个表中(这是最终目标),我无法找到此代码的任何语法变体,而这些变体不会引发一个或多个错误。有人可以帮我把这些放在一起吗?
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
“MyCTE'。”附近的语法不正确。
或者流行的
Msg 156,Level 15,State 1,Line 2
关键字' WITH'附近的语法不正确。Msg 319,Level 15,State 1,Line 2
关键字'与'附近的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。Msg 102,Level 15,State 1,Line 9
')'附近的语法不正确。
如果我插入建议的分号,它会以
响应Msg 102,Level 15,State 1,Line 1
&#39 ;;'附近的语法不正确。
所以它让我觉得我不知道我在这里做了什么,而且SQL也没有。
答案 0 :(得分:2)
将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