根据单词分割字符串

时间:2020-01-07 18:08:12

标签: sql string split sql-server-2012 keyword

我在表列中存储了一些JSON数据作为TEXT。下面是一栏中包含的部分内容。

我想做的是获取当前为col1的文本和之前为col2的文本。不知道如何去做。任何帮助将不胜感激

$ helm template efs-provisioner stable/efs-provisioner \
  --set efsProvisioner.efsFileSystemId=fs-a1b2c3d4 \
  --set efsProvisioner.awsRegion=us-east-1 \
  --set annotations."ad\.datadoghq\.com/tags"="\{\"env\": \"staging\"\}" 

1 个答案:

答案 0 :(得分:0)

由于我们没有较新版本的SQL Server提供的JSON解析器,因此如果您的JSON字符串的结构是静态的,则这是一种丑陋的方法,可能会奏效。为简单起见,我假设除了要提取的特定字符串中没有其他空格。因此,您可能需要在此代码中调整一些数字(11,12,13)来解决这个问题。如果您经历了它,您将会发现它基本上是一种分治法来获取我们想要的字符串。

with your_table as

(select '{"field_text":{"current":"This is current text","previous":"This is previous text"},"CustomerIDs":{"current":"1234","previous":""}}' as json_text)

select json_text, txt1, txt2
from your_table t1
cross apply (select charindex('"current":"',json_text) as i1) t2
cross apply (select charindex('"previous":"',json_text,(i1 + 1)) as i2) t3
cross apply (select substring(json_text,(i1+11),(i2-i1-13)) as txt1) t4
cross apply (select charindex('"previous":"',json_text) as i3) t5
cross apply (select charindex('"},',json_text,(i3 + 1)) as i4) t6
cross apply (select substring(json_text,(i3+12),(i4-i3-12)) as txt2) t7;

DEMO ON SQL SERVER 2012