如何在SQL Server 2012中解析JSON字符串

时间:2018-09-20 02:58:51

标签: json sql-server

我有一个json字符串数据。

{ "salesremarks": { "InternalCode":0, "Remark":"" },
  "OTH": { "ZALO_DYN":"", "Payment_mode":"1", "Max_req_EIR":"55" }........

在SQL Server 2012中是否可以解析此数据类型?

我为此使用了字符串函数,但它们也失败了

1 个答案:

答案 0 :(得分:0)

SQL Server 2016具有解析它的功能,对于以前的版本,您将需要自己解析它。这是示例数据的解析示例:

declare @STRING varchar(max);
declare @SalesRemarks_InternalCode varchar(256);
declare @SalesRemarks_Remark varchar(256);
declare @OTH_ZALO_DYN varchar(256);
declare @OTH_Payment_mode varchar(256);
declare @OTH_Max_req_EIR varchar(256);

set @STRING = '{ "salesremarks": { "InternalCode":0, "Remark":"" }, "OTH": { "ZALO_DYN":"", "Payment_mode":"1", "Max_req_EIR":"55" } }'

set @SalesRemarks_InternalCode = substring(@STRING, charindex('"InternalCode"', @STRING) + 15, charindex(',', substring(@STRING, charindex('"InternalCode"', @STRING) + 16, 8000)))    
set @SalesRemarks_Remark = substring(@STRING, charindex('"Remark"', @STRING) + 10, charindex('"', substring(@STRING, charindex('"Remark"', @STRING) + 10, 8000)) - 1)    
set @OTH_ZALO_DYN = substring(@STRING, charindex('"ZALO_DYN"', @STRING) + 12, charindex('"', substring(@STRING, charindex('"ZALO_DYN"', @STRING) + 12, 8000)) - 1)    
set @OTH_Payment_mode = substring(@STRING, charindex('"Payment_mode"', @STRING) + 16, charindex('"', substring(@STRING, charindex('"Payment_mode"', @STRING) + 16, 8000)) - 1)    
set @OTH_Max_req_EIR = substring(@STRING, charindex('"Max_req_EIR"', @STRING) + 15, charindex('"', substring(@STRING, charindex('"Max_req_EIR"', @STRING) + 15, 8000)) - 1)

select @SalesRemarks_InternalCode as SalesRemarks_InternalCode, @SalesRemarks_Remark as SalesRemarks_Remark, @OTH_ZALO_DYN as OTH_ZALO_DYN, @OTH_Payment_mode as OTH_Payment_mode, @OTH_Max_req_EIR as OTH_Max_req_EIR

结果:

+---------------------------+---------------------+--------------+------------------+-----------------+
| SalesRemarks_InternalCode | SalesRemarks_Remark | OTH_ZALO_DYN | OTH_Payment_mode | OTH_Max_req_EIR |
+---------------------------+---------------------+--------------+------------------+-----------------+
| 0                         |                     |              | 1                | 55              |
+---------------------------+---------------------+--------------+------------------+-----------------+