Search code examples
sqlazure-sql-databaseopen-json

How to implement OPENJSON Having JSON code as a text inside a column. How do i use OPENJSON on the column of a table in AZURE SQL Dataware House?


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".

Solution

  • I've updated my answer, please add ; after the insert statement.

    1. 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"}]');
    
    
    1. 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;
    

    3.The result is as follows:
    enter image description here