Eg: RAW DATA
| ORDER# | SUBORDER# | DISCOUNTS | |------- |-----------| -------------------------------| | 1 | 1-123 | '[{ discount:"1",amount:"1"}]' | | 1 | 1-123 | '[{ discount:"2",amount:"2"}]' |
Want to apply OPENJSON on Discounts and have below OUTPUT:
| ORDER# | SUBORDER# | discount | amount | |------- |-----------| ---------|------------| | 1 | 1-123 | 1 | 1 | | 1 | 1-123 | 2 | 2 | Msg 137, Level 15, State 2, Line 44 Must declare the scalar variable "@discounts".
Advertisement
Answer
I’ve updated my answer, please add ;
after the insert statement.
- Create table and insert two rows:
create table dbo.test( ORDER# varchar(255), SUBORDER# varchar(255), DISCOUNTS varchar(255) ); insert into dbo.test values ('1','1-123','[{ "discount":"1","amount":"1"}]'); insert into dbo.test values ('1','1-123','[{ "discount":"2","amount":"2"}]');
- Then we can use following sql to query the data.
select ORDER#,SUBORDER#,A.* from dbo.test t CROSS APPLY OPENJSON(t.DISCOUNTS) WITH ( discount varchar(255), amount varchar(255) ) A;