2017-07-31 44 views
0

這是我的表和數據的SQL Server 2016 JSON結果結構陣列

enter image description here

我的查詢:

SELECT [Name] 
    FROM [TestDB].[dbo].[MyCategory] 
WHERE [Category] = 'A' 
    FOR JSON AUTO 

結果:

[ 
    {"Name": "John"}, 
    {"Name": "Mary"}, 
    {"Name": "Dick"} 
] 

但我想結果如:

["John", "Mary", "Dick"] 
+0

看Magne Rekdal的答案在這裏:https://stackoverflow.com/questions/37708638/sql-to-json-array-of-object s-to-array-of-values-in-sql-2016 – Santiago

回答

0
declare @stra varchar (200) 
set @stra = '' 

select top 5 @stra = 
    case when @stra = '' 
    then '["'+ Name 
    else @stra + coalesce('","' + Name, '') 
    end 
    from [TestDB].[dbo].[MyCategory] 

    set @stra= @stra +'"]' 
print @stra 
+1

'SELECT @v = @v + ...'可能是未定義的,它不是字符串連接的安全方法。 – lad2025

0

我不認爲這JSON格式在FOR JSON條款的支持,看到this article,雖然串["John","Mary","Dick"]使用ISJSON功能被認爲是有效的JSON。

你唯一的辦法很可能是自己修改的輸出是這樣的:

SET NOCOUNT ON 

DECLARE @MyCategory TABLE (ID int , Category char(1), [Name] varchar(50)) 

INSERT INTO @MyCategory VALUES (1, 'A', 'John') 
INSERT INTO @MyCategory VALUES (2, 'A', 'Mary') 
INSERT INTO @MyCategory VALUES (3, 'A', 'Dick') 
INSERT INTO @MyCategory VALUES (4, 'B', 'Sam') 

DECLARE @MyJSON varchar(max) 
SELECT @MyJSON = 
REPLACE(
REPLACE(
(
SELECT [Name] AS ReplaceMe 
    FROM @MyCategory 
WHERE [Category] = 'A' 
    FOR JSON AUTO 
    ), '{"ReplaceMe":','' 
    ) , '}','') 

PRINT @MyJSON 
PRINT ISJSON(@MyJSON) 

輸出到:

["John","Mary","Dick"] 
1