用逗号分割字符串,插入两列的功能

时间:2013-10-08 12:45:31

标签: sql sql-server stored-procedures user-defined-functions

我正在尝试创建一个函数,该函数将用逗号分割并插入带有'Num'和'String'列的表中。

输入字符串看起来像

数字位于num列中,名称位于字符串列中。

到目前为止我已经

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

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

\ 干杯

1 个答案:

答案 0 :(得分: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