Created
August 15, 2020 01:33
-
-
Save jingyang-li/070cb24455e9855e82cd5096a55cf726 to your computer and use it in GitHub Desktop.
Parse data with JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Declare @rept table(Id int Identity(1,1), ReptDesc varchar(max)) | |
Insert into @rept (ReptDesc) | |
Values( | |
'Category: Projects; Accounting and Operations; Sales | |
Description: this is a transaction report'), | |
('Category: Technical, Accounting | |
Description:'), | |
('Category: Accounting'), | |
('Category: Accounting, Sales'), | |
(Null), | |
(Null) | |
--SQL Server 2016 or up versions | |
;with mycte as ( | |
Select * , replace(replace(replace(replace(replace(replace(ReptDesc,char(10),''),char(13),''), | |
'Category:','{"Category":["'),',','","'), ';','","'),'Description:','"], "Description":["')+'"]}' jsonCol | |
from @rept | |
) | |
select id | |
,c.value as Category | |
,d.value as Description | |
from mycte | |
CROSS APPLY OPENJSON(jsoncol, '$.Category') AS c | |
Outer APPLY OPENJSON(jsoncol, '$.Description') AS d | |
/* | |
id Category Description | |
1 Projects this is a transaction report | |
1 Accounting and Operations this is a transaction report | |
1 Sales this is a transaction report | |
2 Technical | |
2 Accounting | |
3 Accounting NULL | |
4 Accounting NULL | |
4 Sales NULL | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment