Sql 插入参数值和JSON字符串值
我试图创建一个存储过程,通过Sql 插入参数值和JSON字符串值,sql,json,sql-server,tsql,Sql,Json,Sql Server,Tsql,我试图创建一个存储过程,通过JSON和参数插入数据 Declare @PaymentJson Nvarchar(1000) = N'{"type":4},{"type":1`},{"type":2},{"type":3}' ,@ProductID bigint = 5 ,@UserCode bigint = 2 Insert into PaymentType ([ProductID], [PaymentT
JSON
和参数插入数据
Declare @PaymentJson Nvarchar(1000) = N'{"type":4},{"type":1`},{"type":2},{"type":3}'
,@ProductID bigint = 5
,@UserCode bigint = 2
Insert into PaymentType ([ProductID], [PaymentType],[UserCode])
SELECT @ProductID,
PaymentType = MAX(CASE WHEN LOWER([key]) = 'type' THEN [value] END),
@UserCode
FROM OPENJSON(@PaymentJson)
结果不是真的,是第一行JSON(在本例中类型是4)
(1行受影响)
我需要,在这种情况下,插入行PaymentType
中所需的JSON
字符串数应为:
(4行受影响)
My DBMS is SQL Server 2019此意外行为的原因是,输入的JSON无效(多个根元素),但OPENJSON()
成功地从无效的JSON解析第一个对象(尽管ISJSON()
返回0
)。作为一种解决方法,您需要将输入JSON转换为有效的JSON数组,并使用OPENJSON()
和带有适当列定义的显式模式对其进行解析:
DECLARE
@PaymentJson nvarchar(1000) = N'{"type":4},{"type":1},{"type":2},{"type":3}',
@ProductID bigint = 5,
@UserCode bigint = 2
INSERT INTO PaymentType ([ProductID], [PaymentType], [UserCode])
SELECT
@ProductID,
[Type],
@UserCode
FROM OPENJSON(CONCAT('[', @PaymentJson, ']')) WITH ([Type] int '$.type')
首先,JSON字符串无效,它必须是数组
N'[{"type":4},{"type":1},{"type":2},{"type":3}]'
其次,您不需要在select语句中使用聚合函数
因此,您的代码应该如下所示:
Declare @PaymentJson Nvarchar(1000) = N'[{"type":4},{"type":1},{"type":2},{"type":3}]'
,@ProductID bigint = 5
,@UserCode bigint = 2
Insert into PaymentType ([ProductID], [PaymentType],[UserCode])
SELECT @ProductID,
PaymentType = (CASE WHEN LOWER([key]) = 'type' THEN [value] END),
@UserCode
FROM OPENJSON(@PaymentJson)
您好,我尝试了一下,我有一个错误:无法将值NULL插入“PaymentType”列、表“PaymentType”中;列不允许空值。插入失败。然后注释insert并使用select,它的tru,return NULL谢谢你的详细回答,它工作正常。
Declare @PaymentJson Nvarchar(1000) = N'[{"type":4},{"type":1},{"type":2},{"type":3}]'
,@ProductID bigint = 5
,@UserCode bigint = 2
Insert into PaymentType ([ProductID], [PaymentType],[UserCode])
SELECT @ProductID,
PaymentType = (CASE WHEN LOWER([key]) = 'type' THEN [value] END),
@UserCode
FROM OPENJSON(@PaymentJson)