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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.