两个定界符之间的字符串('_')

时间:2018-11-01 12:27:17

标签: sql-server string substring charindex

我正在努力将字符串分成基本组成部分。我已经弄清楚了第一部分并且工作正常;

SELECT(SUBSTRING(Field,0,CHARINDEX('_',Field,0))) AS POS1

我目前遇到的问题是第二部分和第三部分。整个字符串的格式为; character_character_character (其中每个字段可以包含不同数量的字符)。

SUBSTRING(Field, CHARINDEX('-',Field)+1, CHARINDEX('_',Field, CHARINDEX('_',Field)+1 - CHARINDEX('_',Field)-1)) AS POS2

这在某些情况下有效,但在其他情况下会被截断。我一直盯着这个看了很久,以至于我对解决方案视而不见。

另外,要解决第三位置。

对于为什么这样做会按应有的方式提出的任何建议都将受到欢迎。

5 个答案:

答案 0 :(得分:2)

如果始终是三个部分,则可以对replaceparsename使用技巧:

SELECT PARSENAME(val, 3) As col1,
       PARSENAME(val, 2) As col2,
       PARSENAME(val, 1) As col3
FROM Table
CROSS APPLY
(
    SELECT REPLACE(Col, '_', '.') As val
) x

答案 1 :(得分:0)

我以前使用REVERSE来做与路径和文件名类似的事情。也有一些示例Here

DECLARE @full VARCHAR(MAX)
SET @full = 'c:\windows\system\sub-folder\somefile_file-stuff.qqq'
SELECT SUBSTRING(@full, 1, LEN(@full)-(CHARINDEX('\',REVERSE(@full))-1)) AS Path

答案 2 :(得分:0)

尝试一下, 我倾向于使用变量来获取职位,而只是获取过程

declare @field varchar(300) =  'character1_character2_character3'
declare @char1Pos int =  CHARINDEX('_',@field,0)

--select @char1Pos
declare @char2Pos int = (CHARINDEX('_',@field)+@char1Pos + 1) -1
--select @char2Pos

select  (SUBSTRING(@field,0,@char1Pos)) AS POS1,
SUBSTRING(@field, -- field
          @char1Pos+ 1,--starting position for POS2
          (@char2Pos -1) - @char1Pos) --ENDING POSITION FOR POS2
          AS POS2,
     substring(@field,-- field
                ((@char2Pos +1) ),--starting position for POS3
                len(@field) - ((@char2Pos -1) - @char1Pos))--ENDING POSITION FOR POS2
                 as POS3

答案 3 :(得分:0)

这应该有效:

SELECT Field, SUBSTRING(Field,0,CHARINDEX('_',Field,0)) AS POS1, 
SUBSTRING(SUBSTRING(Field, CHARINDEX('_',Field)+1, LEN(Field)), 0, CHARINDEX('_',SUBSTRING(Field, CHARINDEX('_',Field)+1, LEN(Field)),0)) AS POS2 ,
SUBSTRING(Field, 3 + LEN(SUBSTRING(Field,0,CHARINDEX('_',Field,0))) + LEN(SUBSTRING(SUBSTRING(Field, CHARINDEX('_',Field)+1, LEN(Field)), 0, CHARINDEX('_',SUBSTRING(Field, CHARINDEX('_',Field)+1, LEN(Field)),0))), LEN(Field))  AS POS3
FROM YOUR_TABLE

答案 4 :(得分:0)

最终工作代码;

SELECT (SUBSTRING([field],0,CHARINDEX('_',[field],0))) AS POS1
, SUBSTRING(SUBSTRING([field], CHARINDEX('_',[field])+1, LEN([field])), 0, CHARINDEX('_',SUBSTRING([field], CHARINDEX('_',[field])+1, LEN([field])),0)) AS POS2
, RIGHT([field],CHARINDEX('_',REVERSE([field]))-1) AS POS3
FROM TableName

谢谢,特别是Sorix。