SQL UNIONs that use the WITH statement
I have to run this query on 20 databases to produce one unified report. I've done this before with a UNION. Is there any way to reuse the WITH statement for each sub-query? I am receiving an error saying that the previous statement must be terminated with a semicolon. Could there be a better way of doing this?
WITH
DUPS (DocNum)
AS (
SELECT DocNum
FROM Akron.dbo.PWZ3
INNER JOIN Akron.dbo.OPWZ T5 ON T5.IdNumber = PWZ3.IdEntry
WHERE T5.PmntDate = '3/10/2011'
GROUP BY DocNum
HAVING COUNT(1) > 1;
)
SELECT PWZ3.IdEntry, PWZ3.DocNum, 'ARK' + PWZ3.CardCode, QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM Akron.dbo.PWZ3 PWZ3
INNER JOIN DELAWARE.dbo.OPWZ T5 ON T5.IdNumber = PWZ3.IdEntry
LEFT JOIN Dups ON DUPS.DocNum = PWZ3.DocNum
WHERE T5.PmntDate = '3/1开发者_JAVA技巧0/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'
AND Dups.DocNum is null
The WITH
statement indicates that the query expressed within the AS
clause is a Common Table Expression (CTE).
If you're asking if you can write more than one query that uses a CTE, then the answer is no. The closest approximation would be creating an inline table-valued function.
(The simple definition of an ordinary table-valued function versus an inline table-valued function is that the inline version is defined only as a query, much like a CTE; you can't do any procedural operations within the function, including declaring/assigning variables).
The following works for me:
WITH stuff AS ( ... some select ) SELECT some_col FROM some_table JOIN stuff ON ... UNION ALL SELECT other_col FROM other_table JOIN stuff ON ...
Tested on PostgreSQL and Oracle
精彩评论