4 回答

TA貢獻(xiàn)1828條經(jīng)驗 獲得超13個贊
您可以在SQL用戶定義函數(shù)中找到解析分隔字符串的解決方案(來自代碼項目)。
你可以使用這個簡單的邏輯:
Declare @products varchar(200) = '1|20|3|343|44|6|8765'Declare @individual varchar(20) = nullWHILE LEN(@products) > 0BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual ENDEND

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊
我不相信SQL Server有內(nèi)置的拆分功能,所以除了UDF之外,我知道的唯一其他答案是劫持PARSENAME函數(shù):
SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2)
PARSENAME接受一個字符串并將其拆分為句點字符。它需要一個數(shù)字作為它的第二個參數(shù),并且該數(shù)字指定要返回的字符串的哪個段(從后到前工作)。
SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello
顯而易見的問題是字符串已經(jīng)包含句點。我仍然認(rèn)為使用UDF是最好的方法......任何其他建議?

TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
首先,創(chuàng)建一個函數(shù)(使用CTE,公共表表達(dá)式不需要臨時表)
create function dbo.SplitString
(
@str nvarchar(4000),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
@str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)
GO
然后,將它用作任何表(或修改它以適合您現(xiàn)有的存儲過程),就像這樣。
select s
from dbo.SplitString('Hello John Smith', ' ')
where zeroBasedOccurance=1
更新
對于長度超過4000個字符的輸入字符串,以前的版本將失敗。此版本負(fù)責(zé)限制:
create function dbo.SplitString
(
@str nvarchar(max),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
@str,
a,
case when b > 0 then b-a ELSE LEN(@str) end)
AS s
from tokens
);
GO
用法保持不變。
添加回答
舉報