我正在尝试从model_interested
列中拆分值,以便仅从整个数据模型显示中
SELECT SUBSTRING(model_interested, 20, CHARINDEX('model', model_interested)) AS model_interested
FROM cust
从model_interested
列中的图像中,我只希望显示
"model":"A180"
"model":"A200 AMG FL"
我尝试按字符数进行拆分,但我认为这不是正确的方法。
答案 0 :(得分:1)
您可以通过SUBSTRING
和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
要获取整个属性(具有属性名称和值),可以使用以下解决方案:
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
您还可以使用JSON_VALUE
获取期望值,但是必须将数据更改为有效的JSON值:
SELECT JSON_VALUE(REPLACE(REPLACE(model_interested, '{[', '[{'), ']}', '}]'), '$[0].model')
FROM table_name
答案 1 :(得分:0)
如果使用的SQL Server版本早于2016,则您可以将查询编写为:
;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