在字符串中查找分隔符的位置(SQL Server)

时间:2009-12-17 21:06:49

标签: sql sql-server-2005 tsql split

我有一个字符串变量

测试=哈里亚| 123 | MALE | STUDENT | HOUSEWIFE

我使用 | 作为分隔字符。如果我想从第二次出现的管道中提取数据直到第三次出现。我需要从字符串上面获得'MALE'。

任何帮助表示赞赏

3 个答案:

答案 0 :(得分:4)

未测试

SELECT
    SUBSTRING (
       @test,
       CHARINDEX('|', @test, CHARINDEX('|', @test) + 1) + 1,
       CHARINDEX('|', @test, CHARINDEX('|', @test, CHARINDEX('|', @test) + 1) + 1) - 1
    )

更好的方法是将字符串拆分为表,并使用ROW_NUMBER()来提取第3个元素。基于此Arrays and Lists in SQL Server

DECLARE @test varchar(100) = 'HARIA|123|MALE|STUDENT|HOUSEWIFE'

SELECT TOP 8000
    Num
INTO
    #Number
FROM
    (
    SELECT
       ROW_NUMBER() OVER (ORDER BY c1.object_id) AS Num
    FROM
       sys.columns c1, sys.columns c2, sys.columns c3
    ) N

SELECT
    ROW_NUMBER() OVER (ORDER BY Num) AS Rank,
    LTRIM(RTRIM(SUBSTRING(@test,
                          Num,
                          CHARINDEX('|', @test + '|', Num) - Num
                ))) AS Value
FROM
    #Number
WHERE
    Num <= LEN (@test)
    AND
    SUBSTRING('|' + @test, Num, 1) = '|'

DROP TABLE #Number

答案 1 :(得分:3)

试试这个

解决方案1 ​​:(使用数字表)

declare @str varchar(1000)
set @str ='HARIA|123|MALE|STUDENT|HOUSEWIFE'
--Creating a number table
;with numcte as( 
select 1 as rn union all select rn+1 from numcte where rn<LEN(@str)),
--Get the position of the "|" charecters
GetDelimitedCharPos as(
select ROW_NUMBER() over(order by getdate()) seq, rn,delimitedcharpos
from numcte 
cross apply(select SUBSTRING(@str,rn,1)delimitedcharpos) X where delimitedcharpos = '|')

--Applying the formula SUBSTRING(@str,startseq + 1,endseq-startseq + 1)
-- i.e. SUBSTRING(@str,11,15-11) in this case

select top 1 SUBSTRING(
    @str
    ,(select top 1 rn+1 from GetDelimitedCharPos where seq =2)
    ,(select top 1 rn from GetDelimitedCharPos where seq =3) - 
    (select top 1 rn+1 from GetDelimitedCharPos where seq =2)
    ) DesiredResult
from GetDelimitedCharPos

解决方案2 :(使用XQuery)

DECLARE @xml as xml,@str as varchar(100),@delimiter as varchar(10)
SET @str='HARIA|123|MALE|STUDENT|HOUSEWIFE'
SET @xml = cast(('<X>'+replace(@str,'|' ,'</X><X>')+'</X>') as xml)
SELECT ShrededData as DesiredResult FROM(
SELECT 
ROW_NUMBER() over(order by getdate()) rn
,N.value('.', 'varchar(10)') as ShrededData FROM @xml.nodes('X') as T(N))X
WHERE X.rn = 3 -- Specifying the destination sequence value(here 3)

输出(在两种情况下)

DesiredResult
MALE

答案 2 :(得分:0)

我找到了this。使用t-Sql进行循环。语法的良好参考。