SQL Server How to use multiple with statements along with UNION ALL in SQL?

ocebsuys  于 2023-04-19  发布在  其他
关注(0)|答案(3)|浏览(128)
WITH L1 AS
(
   SELECT
)
SELECT A FROM L1

UNION ALL

SELECT A FROM TABLE

UNION ALL

WITH L2 AS
(
   SELECT
)
SELECT A FROM L2

UNION ALL

WITH L3 AS
(
   SELECT
)
SELECT A FROM L3

I get an error

Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon."

Please help

0dxa2lsx

0dxa2lsx1#

You cannot use WITH in the middle of a query expression. WITH is used to build up intermediate queries for use by other queries immediately after (meaning it cannot be used by multiple independent queries).

So you probably want something like:

WITH L1 
AS
(
    SELECT ...
),
L2 AS
(
    SELECT ...
),
L3 AS
(
    SELECT ...
)

// begin final query    
SELECT A FROM L1
UNION ALL
SELECT A FROM TABLE
UNION ALL
SELECT A FROM L2
UNION ALL
SELECT A FROM L3
68de4m5k

68de4m5k2#

The syntax is

With l1 ( a ) as ( Select ... )
   , l2 ( a ) as ( ... )
  Select ... From ...
  Union
  Select ... From ...
58wvjzkj

58wvjzkj3#

Two ways to do this:

SELECT A FROM L1
UNION ALL
SELECT A FROM L2
UNION ALL
SELECT A FROM L3

OR

WITH CTE_L AS
(
    SELECT A FROM L1
    UNION ALL
    SELECT A FROM L2
    UNION ALL
    SELECT A FROM L3
)
SELECT * FROM CTE_L

相关问题