0

我正在尝试创建一个函数,该函数将用逗号分隔并插入到具有“Num”和“String”列的表中。

输入字符串看起来像

数字位于 num 列中,名称位于 string 列中。

到目前为止我有

drop function dbo.GetCommaSplit;
go

CREATE FUNCTION dbo.GetCommaSplit (@String varchar(max))
RETURNS table
AS
RETURN 
(
WITH Splitter (Num, String)
AS

FROM dbo.Numbers
WHERE Num <= LEN(@String)
AND (SUBSTRING(@String, Num - 1, 1) = N',' OR Num = 0)
)
SELECT
RTRIM(LTRIM(String)) AS Word
FROM Splitter
WHERE String <> ''
);
GO

但这会拆分所有内容并每次都给出一个新行,这不是我想要的。

\ 干杯

4

1 回答 1

0

就像是

;with cte as
(
select 
    1 as rn, 
    CHARINDEX(',',@string, 0) pos, 
    LEFT(@string,CHARINDEX(',',@string, 0) -1) as word, 
    substring(@string,CHARINDEX(',',@string, 0) +1, LEN(@string)) as string
union all
select
    rn+1,
    CHARINDEX(',',string, 0) pos, 
    case when CHARINDEX(',',string, 0) >0 then  LEFT(string,CHARINDEX(',',string, 0) -1) else string end as word, 
    case when CHARINDEX(',',string, 0) >0 then  substring(string,CHARINDEX(',',string, 0) +1, LEN(string)) else null end as string
from cte
where CHARINDEX(',',string, 0) >=0
)
select c1.word as Num, c2.word as Name from    
(select * from cte where rn %2=0) c1
inner join
(select * from cte) c2
    on c1.rn =c2.rn+1
于 2013-10-08T13:13:24.490 回答