Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

SQL to JSON - How to get query output without column names then put together the two columns

For example, a table called User has columns FirstName and LastName. So when I query

SELECT * FROM User FOR JSON PATH

The output is

[{ "FirstName": "Bruce",
   "LastName": "Wayne"
}]

But the output I am trying to get is

[{ "Bruce" : "Wayne" }]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In JSON, the structure is "Property" : "Value". You are attempting to create a JSON with the structure "Value" : "Value".
I'm not sure why you would want such a thing or even if it's a good idea, but to get to this you can create the output string yourself as gotqn suggested in his comment instead of using FOR JSON.

First, create and populate sample table (Please save us this step in your future questions):

CREATE TABLE [user]
(
    FirstName varchar(10),
    LastName varchar(10)
)

INSERT INTO [User] (FirstName, LastName) VALUES 
('Bruce', 'Wayne'),
('Clark', 'Kent'),
('Peter', 'Parker'),
('Tony', 'Stark')

The query:

SELECT STUFF(
    (
    SELECT ',{"'+ FirstName +'" : "'+ LastName +'"}' 
    FROM [User]
    FOR XML PATH('')
    )
, 1, 1, '[') + ']' As JsonOutput

Results:

JsonOutput
[{"Bruce" : "Wayne"},{"Clark" : "Kent"},{"Peter" : "Parker"},{"Tony" : "Stark"}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...