仅在特殊字符串之前选择String

时间:2017-04-14 07:05:12

标签: sql sql-server

这是table1中的数据column1

  • “errorList”: “017519033:的 815 下,”, “的errorCode”: “139”

  • “errorList”: “0115101233:的 815 下,”, “的errorCode”: “139”

  • “errorList”: “01815081233:的 805 下,”, “的errorCode”: “19”

  • “errorList”: “018995081233:的 805 下,”, “的errorCode”: “815”

我想在“:”之后选择包含815的数据 任何想法怎么做?

我的预期输出:

  • “errorList”: “017519033:的 815 下,”, “的errorCode”: “139”

  • “errorList”: “0115101233:的 815 下,”, “的errorCode”: “139”

6 个答案:

答案 0 :(得分:0)

如何关注

select * from table1 where column1 like 'errorList":"%:815%'

答案 1 :(得分:0)

您可以使用LikeCharIndex

SELECT * FROM yourTable WHERE column1 LIKE '%:815%'

OR

SELECT * FROM yourTable WHERE charindex(':815', column1) > 0

答案 2 :(得分:0)

这应该有效:

select * from mytable where column1 like '%:815,%'

答案 3 :(得分:0)

select * from your_table 
where 
right(errorList, len(errorlist) - charindex(':', errorlist)) = 815

答案 4 :(得分:0)

另一种使用XML进行字符串拆分的解决方案:

DECLARE @tbl TABLE(YourString VARCHAR(100));
INSERT INTO @tbl VALUES
 ('"errorList":"017519033:815,","errorCode":"139"')
,('"errorList":"0115101233:815,","errorCode":"139"')
,('"errorList":"01815081233:805,","errorCode":"19"')
,('"errorList":"018995081233:805,","errorCode":"815"');


SELECT *
FROM @tbl 
WHERE LEFT(CAST('<x>' + REPLACE(YourString,':','</x><x>') + '</x>' AS XML).value('(/x)[3]','nvarchar(max)'),3)='815'

这种方法的最大优点是,您可以使用索引访问字符串的任何部分,在许多情况下是类型安全的......

更新检查

DECLARE @tbl TABLE(ID INT IDENTITY,YourString VARCHAR(100));
INSERT INTO @tbl VALUES
 ('"errorList":"017519033:815,","errorCode":"139"')
,('"errorList":"0115101233:815,","errorCode":"139"')
,('"errorList":"01815081233:805,","errorCode":"19"')
,('"errorList":"018995081233:805,","errorCode":"815"');

WITH Casted AS
(
    SELECT ID
          ,YourString
          ,CAST('<x>' + REPLACE(REPLACE(YourString,'"',''),':','</x><x>') + '</x>' AS XML) AS TheXml
    FROM @tbl
)
SELECT TheXml.value('(/x/text())[1]','nvarchar(max)') AS Part1
      ,TheXml.value('(/x/text())[2]','nvarchar(max)') AS Part2
      --,TheXml.value('(/x/text())[3]','nvarchar(max)') AS Part3
      ,Part3a AS Part3
      ,Part3b AS Part4
      ,TheXml.value('(/x/text())[4]','nvarchar(max)') AS Part5
FROM Casted
CROSS APPLY(SELECT TheXml.value('(/x/text())[3]','nvarchar(max)') AS Part3
                  ,CHARINDEX(',',TheXml.value('(/x/text())[3]','nvarchar(max)')) AS PosComma) AS A
CROSS APPLY(SELECT LEFT(Part3,A.PosComma-1) AS Part3a
                  ,SUBSTRING(Part3,A.PosComma+2,1000) AS Part3b) AS B

结果

Part1       Part2           Part3   Part4       Part5
errorList   017519033       815     errorCode   139
errorList   0115101233      815     errorCode   139
errorList   01815081233     805     errorCode   19
errorList   018995081233    805     errorCode   815

答案 5 :(得分:0)

select * from table1 where PATINDEX('%:815%',column1)>1