0

I want to get "OrderNumber" field value from below mentioned json string. Pleas suggest best way to get the same

DECLARE @JSON NVARCHAR(MAX)=

  '{"ErpOrderResponses":[{"OrderSubmitStatus":"Ok","TransactionId":"{5EAB3ADC-EB9B-47F7-98B8-1449E2CC0A6B}","OrderNumber":7000027934,"CustomerNumber":80038707,"Description":"Request Successful","ResponseCode":"Success","ResponseType":"None","Errors":[]}],"IsErpUnavailable":false,"IsSuccessful":true,"IsPartiallySuccessful":false,"IsValidationFailed":false,"IsFailed":false}'

    DECLARE @OrderNumber BIGINT = 
    (SELECT REPLACE(REPLACE(SUBSTRING(@JSON,CHARINDEX('OrderNumber',@JSON)+1,
                                                        CHARINDEX(',',@JSON,
                                                                        CHARINDEX('OrderNumber',@JSON)+1
                                                                )-CHARINDEX('OrderNumber',@JSON)
                                                        )
                                                        ,'RDERNUMBER":',''),',','') )
    --SELECT CAST( @OrderNumber AS BIGINT)

    SELECT  @OrderNumber 
  • What version of Sql Server are you using? – World Wide DBA Mar 3 '19 at 21:58
5

Assuming you are on SQL Server 2016 or greater, you can use the JSON_VALUE function to parse out an individual value:

SELECT  JSON_VALUE(@JSON,'$.ErpOrderResponses[0].OrderNumber');

If you are going to be processing more than one row, I recommend you use OPENJSON for better performance:

SELECT 
    * 
FROM 
    OPENJSON(@JSON,'$.ErpOrderResponses')  
    WITH (OrderSubmitStatus varchar(20),OrderNumber bigint);

Documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-2017

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.