如果某些字符存在SQL,则从字符串中提取子字符串

时间:2017-10-12 13:57:29

标签: sql sql-server

我有一个字符串:

DECLARE @UserComment AS VARCHAR(1000) = 'bjones marked inspection on system UP for site COL01545 as Refused to COD won''t pay upfront  :Routeid: 12 :Inspectionid: 55274'

有没有办法让我在' Inspectionid之后从字符串中提取所有内容:'只留下InspectionID保存到变量?

4 个答案:

答案 0 :(得分:2)

您的示例无法正常工作。您将变量定义为varchar(100),但字符串中的字符数多于此值。

这应该基于您的示例数据。

DECLARE @UserComment AS VARCHAR(1000) = 'bjones marked inspection on system UP for site COL01545 as Refused to COD won''t pay upfront  :Routeid: 12 :Inspectionid: 55274'

select right(@UserComment, case when charindex('Inspectionid: ', @UserComment, 0) > 0 then len(@UserComment) - charindex('Inspectionid: ', @UserComment, 0) - 13 else len(@UserComment) end)

答案 1 :(得分:1)

我会这样做:

select stuff(@UserComment, 1, charindex(':Inspectionid: ', @UserComment) + 14, '')

即使找不到字符串,它仍然有效 - 尽管它将返回整个字符串。在这种情况下获取空字符串:

select stuff(@UserComment, 1, charindex(':Inspectionid: ', @UserComment + ':Inspectionid: ') + 14, '')

答案 2 :(得分:0)

首先,我要说你的@UserComment变量不够长,不能包含你要放入的文本。增加第一个的大小。

下面的SQL将提取值:

DECLARE @UserComment AS VARCHAR(1000); SET @UserComment = 'bjones marked inspection on system UP for site COL01545 as Refused to COD won''t pay upfront  :Routeid: 12 :Inspectionid: 55274'

DECLARE @pos int
DECLARE @InspectionId int
DECLARE @IdToFind varchar(100)

SET @IdToFind = 'Inspectionid: '
SET @pos = CHARINDEX(@IdToFind, @UserComment)
IF @pos > 0
BEGIN
    SET @InspectionId = CAST(SUBSTRING(@UserComment, @pos+LEN(@IdToFind)+1, (LEN(@UserComment) - @pos) + 1) AS INT)
    PRINT @InspectionId
END

如有必要,您可以将上述代码转换为SQL函数。

答案 3 :(得分:0)

如果检验ID总是5位数,则子串函数的最后一个参数(长度)可以是5,即

SELECT SUBSTRING(@UserComment,PATINDEX('%Inspectionid:%',@UserComment)+14,5)

如果检验ID变化(但总是在结尾 - 你的问题略微暗示),那么最后一个参数可以通过减去' InspectionID:'的位置得出。从字符串的总长度。像这样:

SELECT SUBSTRING(@UserComment,PATINDEX('%Inspectionid:%',@UserComment)+14,LEN(@usercomment)-(PATINDEX('%Inspectionid:%',@UserComment)+13))