在SQL Server 2016中处理插入的示例,它结合了常规值和json数据

时间:2017-01-17 02:56:38

标签: json sql-server-2016

作为一个简单的例子,我试图将orderID添加到json数据的每一行的记录中。

declare @orderid as int = 22

declare @jdata as nvarchar(max) = '[{"qty":"5","description":"purple zebras ","clientid":null,"projectid":null,"cost":"179.15"}]'

insert into MB_OrderItems (OrderID)
select @OrderID as OrderID
cross apply 
openjson(@jdata)
with (
    qty int,
    description varchar(100),
    clientID int, 
    projectid int,
    cost decimal(18,2)
    ) as ordersarray

1 个答案:

答案 0 :(得分:0)

此方法获取您的json字符串,将其格式化为表格,将您的订单ID添加为新字段,然后将其放回json字符串。为了获取json字符串中返回的空值,您必须明确告诉sql server返回空值。

declare @orderid as int = 22
declare @jdata as nvarchar(max) = '[{"qty":"5","description":"purple zebras ","clientid":null,"projectid":null,"cost":"179.15"}]'


;with CTE AS (
select *
FROM OPENJSON(@JDATA) 
WITH (qty int '$.qty',
description varchar(100) '$.description',
clientid INT '$.clientid',
projectID INT '$.projectid',
cost money '$.cost',
orderID INT )
)


SELECT 
qty,
description,
clientid, 
projectid, 
cost, 
@orderid AS Orderid 
FROM cte
FOR JSON AUTO, INCLUDE_NULL_VALUES