使用SQL 2016 JSON内置函数
表:用户 列(ID int,FirstName varchar(50),LastName varchar(50)
数据
3009 Emily Manners
3010 Joanne Hernandez
3011 Kelly Kleiner
3012 Alexis Frederick
3013 Dietric Singleton
3018 Ashley Ely
3021 Jeralynn Campbell-Triplett
3026 Lauren Zinnerman
3027 Christopher Correa
3028 Stefanie MontalvoCruz
期望的结果 - >临时表
ID JSON_DATA
3009 {"ID":3009,"FirstName":"Emily","LastName":"Manners"}
3010 {"ID":3010,"FirstName":"Joanne","LastName":"Hernandez"}
尝试使用:
SELECT
[ID],
[FirstName],
[LastName]
FROM Emp
FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER
答案 0 :(得分:3)
在CROSS APPLY
的帮助下Declare @Emp table (ID int,FirstName varchar(50),LastName varchar(50))
Insert into @Emp values
(3009,'Emily' ,'Manners'),
(3010,'Joanne','Hernandez'),
(3011,'Kelly' ,'Kleiner')
Select A.ID
,B.JSON_Data
From @Emp A
Cross Apply (
Select JSON_Data = (Select A.ID,A.FirstName,A.LastName FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)
) B
返回
ID JSON_Data
3009 {"ID":3009,"FirstName":"Emily","LastName":"Manners"}
3010 {"ID":3010,"FirstName":"Joanne","LastName":"Hernandez"}
3011 {"ID":3011,"FirstName":"Kelly","LastName":"Kleiner"}
答案 1 :(得分:0)
在某些情况下,此表格可能比使用交叉申请更具可读性 在我尝试过的情况下,执行计划总是相同的,但在任何特定情况下,执行计划可能比其他计划表现更好。
Declare @Emp table (ID int,FirstName varchar(50),LastName varchar(50))
Insert into @Emp values
(3009,'Emily' ,'Manners'),
(3010,'Joanne','Hernandez'),
(3011,'Kelly' ,'Kleiner')
Select A.ID
,(Select A.ID,A.FirstName,A.LastName
FOR JSON PATH, INCLUDE_NULL_VALUES,
WITHOUT_ARRAY_WRAPPER) AS JSON_Data
From @Emp A