0

I have database table, in a column i have JSON data, in which data was wrongly updated. I know the pattern to remove incorrect node from JSON string.

I am trying to create regex expression to remove node which has "A":"99f7cd78-54c3-40cb-bde4-21f1b826ad86".

Below is JSON string in data column:

[{"A":"957d43b6-07ce-41b4-b7b8-a6098ca08bba","RN":0,"N":"ABC 1%","R":10.00,"T":"b57d51ef-5538-4725-82eb-0f2fad4f1b82"},{"A":"99f7cd78-54c3-40cb-bde4-21f1b826ad86","RN":0,"N":"ABC 1%","R":10.00,"T":"294ac06a-1cd1-4961-8298-6e3b63ebd979"}]

So output string should be : [{"A":"957d43b6-07ce-41b4-b7b8-a6098ca08bba","RN":0,"N":"ABC 1%","R":10.00,"T":"b57d51ef-5538-4725-82eb-0f2fad4f1b82"}]

Can someone guide me what regex i need to use in SQL Server?

I am new to regex.

I tried below regex:

\s*\,\{\"A\":\"99f7cd78-54c3-40cb-bde4-21f1b826ad86\".+?}

I am not sure how to use this regex to remove JSON properties.

1
  • What is the SQL Server version? Commented May 15, 2020 at 19:26

1 Answer 1

2

Starting with SQL Server 2016 you may use built-in JSON support, but you can't remove JSON items from JSON array using regex. One possible approach in this case is to parse the JSON using OPENJSON and get content as table, filter the table with the appropriate WHERE clause and format table rows as JSON using FOR JSON:

Table:

CREATE TABLE Data (JsonColumn varchar(1000))
INSERT INTO Data (JsonColumn)
VALUES ('[
   {"A":"957d43b6-07ce-41b4-b7b8-a6098ca08bba","RN":0,"N":"ABC 1%","R":10.00,"T":"b57d51ef-5538-4725-82eb-0f2fad4f1b82"},
   {"A":"99f7cd78-54c3-40cb-bde4-21f1b826ad86","RN":0,"N":"ABC 1%","R":10.00,"T":"294ac06a-1cd1-4961-8298-6e3b63ebd979"}
]')

Statement:

UPDATE Data
SET JsonColumn = (
   SELECT *
   FROM OPENJSON(JsonColumn) WITH (
      A varchar(50) '$.A',
      RN int '$.RN',
      N varchar(10) '$.N',
      R numeric(5, 2) '$.R',
      T varchar(50) '$.T'
   )
   WHERE A <> '99f7cd78-54c3-40cb-bde4-21f1b826ad86'
   FOR JSON PATH
)

Result:

JsonColumn
[{"A":"957d43b6-07ce-41b4-b7b8-a6098ca08bba","RN":0,"N":"ABC 1%","R":10.00,"T":"b57d51ef-5538-4725-82eb-0f2fad4f1b82"}]
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.