Normally, we can cast a single record query to nvarchar(max)
. For example:
DECLARE @result NVARCHAR(MAX) = N'';
SELECT
@result = @result + (CAST((SELECT TOP(3) name AS td
FROM
sys.databases
FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT @result
But how can I do the same thing when the query has CTE? The query still returns a single row. For example:
DECLARE @result NVARCHAR(MAX) = N'';
SELECT
@result = @result + (CAST((WITH d AS
(SELECT name FROM sys.databases)
SELECT TOP(3) name AS td
FROM d
FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT @result
When I execute it, I got the following errors:
Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 7
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 8
Incorrect syntax near ')'
I know I can use a derived table or subquery etc. But in my case, the query is very complex and it has several CTEs in it, which I don't want to touch.
1条答案
按热度按时间bd1hkmkf1#
CTE定义不应位于select语句上: