0

I need to extract an ID from some a string field (JSON code). From performance perspective what is the best way to obtain this ID and where?

Remarks:

  • there are different type of messages
  • payload: JSON field
  • sample of message type1: {"RequestId":"4B5E95D49D3E46548904083D0CD17521"}
  • sample of message type2:{"createdById":"XXXXXXXXX","requestId":"15F79EC78E5243A487337C0FE61A9E00","sessionId":null}
  • SQL in order to extract the id:
select  
    (Case 
        when eventType = 'Type1' then substring (payload, CHARINDEX('{',payload)+ LEN('{"RequestId":"'),   CHARINDEX ('"}', payload) -( CHARINDEX('{',payload)+ LEN('{"RequestId":"'))) 
        when eventType = ' Type2' then substring (payload, CHARINDEX('"requestId":"',payload)+ LEN('"requestId":"'),   CHARINDEX ('","sessionId"', payload) -(  CHARINDEX('"requestId":"',payload)+ LEN('"requestId":"'))) 
        else 'none' END) as RequestID 
  from table
4
  • 5
    Why use CHARINDEX and SUBSTRING not use SQL Server's JSON functionality? Commented Jun 24, 2021 at 9:47
  • 2
    And your @@version of SQL Server is... - ? Commented Jun 24, 2021 at 9:53
  • SQL Server Management Studio 15.0.18384.0 (Azure) Commented Jun 24, 2021 at 10:58
  • Thanks! Larnu...to tell you the truth , it is really the first time that I'm working in something like this, I'm truly not familiar with these capabilities Commented Jun 24, 2021 at 11:00

1 Answer 1

1

If you are running SQL Server 2016+ then use this query:

select JSON_VALUE(t.payload, '$.requestId') from table t
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.