我正在尝试基于我拥有的JSON更新表中的行。 JSON具有以下结构:
"sensors": [
{
"id": "5afd7160f16819f11814f6e2",
"num": 0,
"name": "AC01",
"enabled": true,
"unit": "Volt AC Phase 1",
"desc": "NAMsdafE",
"lt_disaster": 1,
"gt_disaster": 1,
"lt_high": 1,
"gt_high": 1,
"lt_average": 1,
"gt_average": 1
},...
表dbo.sensors
具有相同的结构+几列。要将这样的JSON对象而不是数组插入表中,我可以这样做:
INSERT INTO dbo.sensors (.......)
SELECT .......
FROM OPENJSON(@json)
WITH (
id varchar(200),
....
);
所以我有两个问题:如何遍历JSON数组中的每个元素,并使用相同的id
更新每一行。任何帮助,将不胜感激:)
答案 0 :(得分:2)
首先,阅读文档OPENJSON。此功能自2016年版本开始可用。
接下来,应用新知识。
--truncated for shortness
--note: wrap JSON string in curly brackets {}
declare @json nvarchar(max)='{"sensors":[
{
"id": "5afd7160f16819f11814f6e2",
"num": 0,
"name": "AC01",
"more": "unused"
},
{ "id": "5afd7160f16819f11814f6e3",
"num": 0,
"name": "AC02"
}]}
'
--insert...
select * from
openjson(@json,'$.sensors') --note the "path" argument here
with(
id varchar(200),
num int,
name varchar(10)
) json --alias sometimes required.
您可以使用结果(行集),因为它是一个表。
答案 1 :(得分:1)
1)一旦将json更改为select语句,就可以使用游标对其进行迭代。
2)您可以将json select语句视为表。也就是说,您可以完全像对两个表一样进行插入,更新,删除操作。对于更新的案例,您可以使用如下代码:
With Json_data as
( SELECT .......
FROM OPENJSON(@json)
WITH (
id varchar(200),
....
)
update S set ....
from dbo.sensors as S
inner join Json_data as JD on JD.id = S.id
答案 2 :(得分:0)
;With Json_data as
( SELECT
Evaluation_IDNO,
Rating_IDNO,
Notes_TEXT,
NextSteps_TEXT,
EvaluationCategory_CODE,
EvalType_ID
FROM OPENJSON(@As_EvaluationCategory_Json) WITH
(
Evaluation_IDNO INT N'$.matrixId',
Rating_IDNO VARCHAR(150) N'$.ratingValue',
Notes_TEXT VARCHAR(MAX) N'$.notesText',
NextSteps_TEXT VARCHAR(MAX) N'$.nextStepsText',
EvaluationCategory_CODE VARCHAR(50) N'$.ratingData',
EvalType_ID VARCHAR(4) N'$.evalTypeId'
)
AS EvaluationCategories
)
UPDATE EvaluationRatings_T1 SET
UserCreatedBy_ID=@As_SignedOnWorker_ID,
User_ID=@Ls_User_Id,
WorkspaceCreatedBy_ID=@Ls_WorkspaceCreatedBy_Id,
BeginValidity_DTTM=@Ls_Evaluation_DTTM,
EndValidity_DTTM=@Ld_HighValidity_DTTM,
TransactionEvenSeq_NUMB=@An_TransactionEventSeq_NUMB,
Update_DTTM=@Ld_BeginValiditiy_DTTM,
WorkspaceUpdatedBy_ID=@Ls_WorkspaceUpdatedBy_ID,
Evaluation_IDNO=c1.Evaluation_IDNO,
Rating_IDNO=c1.Rating_IDNO,
Notes_TEXT=c1.Notes_TEXT,
NextSteps_TEXT=c1.NextSteps_TEXT,
EvaluationCategory_CODE=c1.EvaluationCategory_CODE,
EvalType_ID=c1.EvalType_ID
FROM Json_data c1
inner JOIN EvaluationRatings_T1 e1 on e1.Evaluation_IDNO=c1.Evaluation_IDNO
WHERE e1.Evaluation_IDNO=@AS_Evaluation_IDNO;