skip to Main Content

I have several columns in my database. In one of these columns is a JSON string like: fyvfvv.

[
  {
    "Value": "0000138010687",  
    "Name": "Code"
  }
]

I need to select those rows from the database, whose JSON is filled with the value of the mask "0000****", or the value is greater than a certain number.
Can you tell me how to do it in the best way?

2

Answers


  1. You need to parse the stored JSON with OPENJSON() and use the appropriate WHERE clause.

    Data:

    SELECT *
    INTO JsonTable
    FROM (VALUES
       ('[{"Value": "00001380", "Name": "Code"}]'),
       ('[{"Value": "0000138010688", "Name": "Code"}]'),
       ('[{"Value": "0000138010689", "Name": "Code"}]')
    ) v (JsonColumn)
    

    Statement (to get the rows):

    SELECT *
    FROM JsonTable t
    WHERE EXISTS (
       SELECT 1
       FROM OPENJSON(t.JsonColumn) WITH (
          [Value] varchar(100) '$.Value',
          [Name] varchar(100) '$.Name'
       )
       WHERE [Value] LIKE '0000____'  
    )
    

    Statement (to get the rows and the parsed JSON):

    SELECT *
    FROM JsonTable t
    CROSS APPLY OPENJSON(t.JsonColumn) WITH (
       [Value] varchar(100) '$.Value',
       [Name] varchar(100) '$.Name'
    ) j
    WHERE j.[Value] LIKE '0000____'  
    

    Both statements return the correct results, even if the parsed JSON array contains more than one item.

    Login or Signup to reply.
  2. Assuming the json array contains one element only, then we can use JSON_VALUE() to get the element value by path :

    select *
    from (
      select *, 
        JSON_VALUE(JsonColumn, '$[0].Value') as theValue, 
        JSON_VALUE(JsonColumn, '$[0].Name') as theName
      from JsonTable
    ) as s
    where theName = 'Code' and theValue like '0000%';
    

    Demo here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search