我有一個字符串變量查找字符串分隔符的位置(SQL Server)的
測試=哈里亞| 123 |男|學生|主婦
我使用|作爲分隔符。如果我想從第二次出現的管道提取數據直到第三次出現。我需要從上面的字符串中獲得'MALE'。
任何幫助理解
我有一個字符串變量查找字符串分隔符的位置(SQL Server)的
測試=哈里亞| 123 |男|學生|主婦
我使用|作爲分隔符。如果我想從第二次出現的管道提取數據直到第三次出現。我需要從上面的字符串中獲得'MALE'。
任何幫助理解
未測試
SELECT
SUBSTRING (
@test,
CHARINDEX('|', @test, CHARINDEX('|', @test) + 1) + 1,
CHARINDEX('|', @test, CHARINDEX('|', @test, CHARINDEX('|', @test) + 1) + 1) - 1
)
甲更好的方式將所述字符串分割成一個表,並使用ROW_NUMBER()以提取第三元件。在此基礎上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:(使用數表)
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
我找到this。使用t-Sql for循環。很好的語法參考。