如何在SQL Server中分割字符串

时间:2019-04-22 09:03:52

标签: sql sql-server split

我正在尝试从model_interested列中拆分值,以便仅从整个数据模型显示中

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

model_interested列中的图像中,我只希望显示

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

我尝试按字符数进行拆分,但我认为这不是正确的方法。

2 个答案:

答案 0 :(得分:1)

您可以通过SUBSTRINGCHARINDEX使用以下解决方案:

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

demo on dbfiddle.uk

答案 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

演示在这里:https://rextester.com/CCW41495