SQL Server 如何将具有CTE的查询转换为nvarchar(max)?

vwkv1x7d  于 2022-12-10  发布在  其他
关注(0)|答案(1)|浏览(116)

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.

bd1hkmkf

bd1hkmkf1#

CTE定义不应位于select语句上:

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

相关问题