0

I'm trying to split the value from the model_interested column so that from the whole data only model display

SELECT SUBSTRING(model_interested, 20, CHARINDEX('model', model_interested)) AS model_interested 
FROM cust

From the image in model_interested column I wish to only display

"model":"A180"
"model":"A200 AMG FL"

I have tried splitting by number of characters but I don't think it's the right way.

2

2 Answers 2

1

You can use the following solution using SUBSTRING and CHARINDEX:

SELECT SUBSTRING(model_interested, CHARINDEX('"model":"', model_interested) + LEN('"model":"'), CHARINDEX('"', model_interested, CHARINDEX('"model":"', model_interested) + LEN('"model":"')) - (CHARINDEX('"model":"', model_interested) + LEN('"model":"')))
FROM table_name

To get the whole property (with property name and value) you can use the following solution:

SELECT SUBSTRING(model_interested, CHARINDEX('"model":"', model_interested), CHARINDEX('"', model_interested, CHARINDEX('"model":"', model_interested) + LEN('"model":"')) - CHARINDEX('"model":"', model_interested) + 1)
FROM table_name

You can also use JSON_VALUE to get the expected value, but you have to change the data to a valid JSON value:

SELECT JSON_VALUE(REPLACE(REPLACE(model_interested, '{[', '[{'), ']}', '}]'), '$[0].model')
FROM table_name

demo on dbfiddle.uk

Sign up to request clarification or add additional context in comments.

Comments

0

If using earlier version of SQL server than 2016, then you can write a query as:

;with cte as
(
 SELECT   
       Split.a.value('.', 'VARCHAR(100)') AS model_interested  
 FROM  (
         SELECT CAST ('<M>' + REPLACE([model_interested], '.', '</M><M>') + '</M>' AS XML)
                as  model_interested_xml
         FROM  @cust

        ) AS A CROSS APPLY model_interested_xml.nodes ('/M') AS Split(a)  
    )
select model_interested
from cte
where CHARINDEX('model',model_interested) > 0

demo here: https://rextester.com/CCW41495

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.