sql - Sql - 打开 Json 插入表
问题描述
我有一部分存储过程检索从我的 Json 接收到的数据,然后我使用了 OPENJSON 以便以表格格式显示。
但是如何将它插入到现有表中,在我的 OpenJson 中具有相同的声明列名?
Declare @JsonString varchar(MAX) = (Select DataReceived from ItemTransaction where
DocType ='LoadItem' and BranchCode = @pBranchCode and TranNo = @pTranNo)
Sample ReplyData string
'{"status":{"code":"0","name":"RCRD_LOADED","status":"Success","message":"Record sucessfully loaded"},"records":[{"recordtype":"inventoryitem","id":"2310","itemid":"00999","displayname":"Neck - Tie","locationquantityonhand":"9996","locationquantityavailable":"9994","locationquantitycommitted":"9994","locationquantitybackordered":"9994"}]}'
SELECT * FROM
OPENJSON ( @JsonString,'$."records"')
WITH (
RecordType varchar(200) '$.recordtype' ,
ItemID varchar '$.id',
ItemDetails varchar(200) '$.itemid',
Quantity int '$.locationquantityonhand'
)
end
解决方案
您可以拥有与 OPENSJSON 具有相似架构的表并将其插入。
CREATE TABLE TestJson
(
RecordType varchar(200)
,ItemID varchar
,ItemDetails varchar(200)
,Quantity int
)
DECLARE @JsonString VARCHAR(MAX) =
'{"status":{"code":"0","name":"RCRD_LOADED","status":"Success","message":"Record sucessfully loaded"},"records":[{"recordtype":"inventoryitem","id":"2310","itemid":"00999","displayname":"Neck - Tie","locationquantityonhand":"9996","locationquantityavailable":"9994","locationquantitycommitted":"9994","locationquantitybackordered":"9994"}]}'
INSERT INTO TestJson
SELECT * FROM
OPENJSON ( @JsonString,'$."records"')
WITH (
RecordType varchar(200) '$.recordtype' ,
ItemID varchar '$.id',
ItemDetails varchar(200) '$.itemid',
Quantity int '$.locationquantityonhand'
)
SELECT * FROM TestJson
+---------------+--------+-------------+----------+
| RecordType | ItemID | ItemDetails | Quantity |
+---------------+--------+-------------+----------+
| inventoryitem | 2 | 00999 | 9996 |
+---------------+--------+-------------+----------+
推荐阅读
- javascript - puppeteer 在所选页面上执行 js 函数
- html - 关于html usemap的一些东西
- haskell - 如何在Haskell中使用doesFileExist函数过滤目录列表?
- android - 使用 ubuntu 和 buildozer 为 android 打包应用程序时出错
- linux - 屏幕记录无法在 ssh 终端上运行
- dart - Flutter 创建无限 ListView.builder 上下滚动
- php - 无法遍历 Laravel POST 中的对象数组
- javascript - 为什么我可以在 Typescript 中将 `Function` 分配给`Interface`?
- c# - 当存在具有实体框架的现有父级时,插入子级的“正确”模式是什么?
- python - Numpy 基于索引值创建数组(Python)