I am trying to write the following SQL.
declare @s varchar(max) = (
with c as (select ...)
select a, b, c, d, ....
from ... join c on .... join c on .... join c on ....
order by ...
for xml raw('...'), elements
);
However, it’s incorrect syntax (The following shows the error message). Do I have to convert it to subqueries? I am trying to avoid to expand the CTE in multiple places.
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.
Update:
The for xml and order by makes select @s = ...
OK, I figured it out. It cannot be done in one declare and initialization statement.