如何使用FOR JSON
从使用通用表表达式(CTE)的select语句中在T-SQL中生成JSON,然后将其存储在局部变量中?
没有CTE,它可能看起来像这样:
DECLARE @var NVARCHAR(MAX) = (
SELECT x.Val
FROM (VALUES (1)) AS x(Val)
FOR JSON AUTO
)
SELECT @var
但是,如果像下面这样使用CTE,语法如何呢?
WITH y AS (
SELECT Val
FROM (VALUES (1)) AS _(Val)
)
SELECT x.Val, y.Val ValY
FROM (VALUES (1)) AS x(Val)
JOIN y ON y.Val = x.Val
FOR JSON AUTO
用DECLARE @var NVARCHAR(MAX) = ( ... )
包围不起作用。
答案 0 :(得分:2)
可能是这样吗?
DECLARE @json NVARCHAR(MAX);
WITH y AS (
SELECT Val
FROM (VALUES (1)) AS _(Val)
)
SELECT @json=
(
SELECT x.Val, y.Val ValY
FROM (VALUES (1)) AS x(Val)
JOIN y ON y.Val = x.Val
FOR JSON AUTO
);
SELECT @json;
此外,您可以将CTE代替“ WITH”作为子查询。实际上,CTE仅仅是“语法糖”,它可以避免重复的子查询并提高SQL的可读性。您可以将其用于同一目的:
DECLARE @json NVARCHAR(MAX)=
(
SELECT x.Val, y.Val ValY
FROM (VALUES (1)) AS x(Val)
JOIN (
SELECT Val
FROM (VALUES (1)) AS _(Val)
) y ON y.Val = x.Val
FOR JSON AUTO
);
SELECT @json