博客列表 >SqlServer常用函数及语法

SqlServer常用函数及语法

葵花宝典
葵花宝典原创
2021年01月22日 14:47:101390浏览

SQL中启用事务,出错回滚

  1. begin tran mytran --启用事务
  2. begin try
  3. select * from rc_pdOrder --要执行的语句
  4. commit tran --执行事务
  5. end try
  6. begin catch
  7. rollback tran --回滚事务
  8. end catch

SQLserver中接处理JSON字符串生成表格,下面的代码复制执行就可以看到结果
看了好多别人写的,都是相互抄, 思路不清晰, 讲不明白原理, 自已写个实例,帮助有需要的人
这段JSON是后端请求数据,数据中有表头部分和表体部分,解晰后生成一个表格,是不是很方便呢

  1. --后端请求的JSON数据
  2. declare @ml nvarchar(max) = N'{"orderCode":"1000092","prdCode":"A0504772","prdName":"复合调味粉M06M06/15kg/袋","factory":"1100",
  3. "mls":[{"id":"1","item":4,"prdCodes":"Z0100390","rsvQty":"225.000","unit":"KG","qty":"225.000","qty1":null,"reservation":757,"rsItem":1,"stockQty":"","whName":"","batCode":"","wh":"","prdNames":"大豆分离蛋白HGK-A807哈高科","potCode":"0102","LAY_TABLE_INDEX":0},
  4. {"id":"2","item":5,"prdCodes":"Z0200567","rsvQty":"15.500","unit":"EA","qty":"15.500","qty1":null,"reservation":757,"rsItem":2,"stockQty":"","whName":"","batCode":"","wh":"","prdNames":"大号公司空白打印标签90×160mm","potCode":"0102","LAY_TABLE_INDEX":1},
  5. {"id":"3","item":6,"prdCodes":"Z0200960","rsvQty":"15.500","unit":"EA","qty":"15.500","qty1":null,"reservation":757,"rsItem":3,"stockQty":"","whName":"","batCode":"","wh":"","prdNames":"25kg印刷牛皮纸袋850×420×80mm","potCode":"0102","LAY_TABLE_INDEX":2}]}'
  6. SELECT orderCode,prdCode,prdName,item,potCode,prdCodes,prdNames,rsvQty,batCode,wh,qty,unit,ordersItem,reservation,rsItem
  7. FROM OPENJSON(@ml)
  8. --这里是取JSON根节点下的键值,表头数据
  9. WITH (
  10. orderCode nvarchar(50) '$.orderCode',
  11. prdCode NVARCHAR(200) '$.prdCode',
  12. prdName NVARCHAR(200) '$.prdName',
  13. mls NVARCHAR(MAX) '$.mls' AS JSON --把根节点下的数组再转成SQL能识的单层JSON
  14. )
  15. OUTER APPLY OPENJSON(mls) --继续解析子级单层JSON,原理比较简单,清晰易懂,拿到的是表体数据
  16. WITH (item NVARCHAR(50) '$.id',
  17. potCode NVARCHAR(50) '$.potCode',
  18. prdCodes nvarchar(50) '$.prdCodes',
  19. prdNames NVARCHAR(50) '$.prdNames',
  20. rsvQty decimal(18,3) '$.rsvQty',
  21. batCode NVARCHAR(50) '$.batCode',
  22. wh NVARCHAR(50) '$.wh',
  23. qty decimal(18,3) '$.qty',
  24. unit NVARCHAR(50) '$.unit',
  25. ordersItem NVARCHAR(50) '$.item',
  26. reservation NVARCHAR(50) '$.reservation',
  27. rsItem NVARCHAR(50) '$.rsItem');

效果图片
SqlServer处理JSON字符串

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议