I have figured out how to recursively find all employees reporting up to a certain manager using Common Table Expressions (Thanks to StackOverflow!).
This is the code that works for me:
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
This works perfectly. But if I try to insert this into another table (which is the ultimate goal) I can't find any syntactical variation of this code that doesn't throw one or more errors. Can someone help me put these together?
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
It is throwing errors like:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'MyCTE'.
Or the ever-popular
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 ')'.
And if I insert the suggested semicolon, it responds with
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ';'.
So it makes me think I don't know what I'm doing here, and neither does SQL.