2017-10-12 95 views
0

我有一个字符串:摘自字符串,如果某些字符串存在SQL

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保存成变量?

回答

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) 
+0

我继续并修复了帖子。这就是说你的反应很完美。谢谢!! – snapper

1

我会做这样的:

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

即使字符串没有发现这工作 - 虽然它会返回整个字符串。在这种情况下获得一个空字符串:

select stuff(@UserComment, 1, charindex(':Inspectionid: ', @UserComment + ':Inspectionid: ') + 14, '') 
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函数。

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))