简体   繁体   English

如何使用 CTE 将查询转换为 nvarchar(max)?

[英]How to cast a query with CTE as nvarchar(max)?

Normally, we can cast a single record query to nvarchar(max) .通常,我们可以将单个记录查询转换为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?但是当查询有 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消息 156,15 级,State 1,第 7 行
Incorrect syntax near the keyword 'WITH'.关键字“WITH”附近的语法不正确。

Msg 319, Level 15, State 1, Line 7消息 319,15 级,State 1,第 7 行
Incorrect syntax near the keyword 'with'.关键字“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.如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前一个语句必须以分号结尾。

Msg 102, Level 15, State 1, Line 8消息 102,15 级,State 1,第 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.我知道我可以使用派生表或子查询等。但在我的例子中,查询非常复杂,其中有几个 CTE,我不想触及。

Your CTE definition should not be on select statement:您的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM