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.
Your CTE definition should not be on select statement:
DECLARE @result NVARCHAR(MAX) = N'';
WITH d AS (SELECT name FROM sys.databases)
SELECT @result = @result + (CAST((SELECT TOP(3) name AS td FROM d FOR XML PATH ('')) AS NVARCHAR(MAX)));
SELECT @result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.