Tạo hàm đọc chuỗi JSON:
https://github.com/khanhmai/Parse-JSON-String-by-SQL-script/blob/master/ParseJSON-FUNCTION.sql
---Hàm này có nhiệm vụ đọc chuỗi JSON-->Đưa thành bảng hàng dọc
Ví dụ:
Select * From
parseJSON
(
'[{"Text":"YES","Value":"YES","Default":true},
{"Text":"NO","Value":"NO","Default":false}]'
)
Kết quả Trả về:
Trong ví dụ trên "giá trị" cột NAME chính là số cột ta cần lấy. Vấn đề bây giờ là chuyển từ cột sang dòng.
Select
max(case when name='Text' then convert(Varchar(50),StringValue) else '' end) as [Text],
max(case when name='Value' then convert(Varchar(50),StringValue) else '' end) as [Value],
max(case when name='Default' then convert(bit,StringValue) else 0 end) as [Default]
From parseJSON
(
'[{"Text":"YES","Value":"YES","Default":true},
{"Text":"NO","Value":"NO","Default":false}]'
)
where ValueType = 'string' OR ValueType = 'boolean'
group by parent_ID
Kết quả đẹp như mơ:

Reference: http://mtkcode.blogspot.sg/2014/08/parse-json-string-by-sql-script.html

Không có nhận xét nào:
Đăng nhận xét