CREATE FUNCTION [dbo].[splitStr] (
@str NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(
RowID smallint IDENTITY(1,1),
t1 NVARCHAR(MAX) ,
t2 NVARCHAR(MAX) ,
t3 NVARCHAR(MAX) ,
t4 NVARCHAR(MAX) ,
t5 NVARCHAR(MAX) ,
t6 NVARCHAR(MAX) ,
t7 NVARCHAR(MAX) ,
t8 NVARCHAR(MAX) ,
t9 NVARCHAR(MAX) ,
t10 NVARCHAR(MAX)
)
begin
declare @st int, @en int, @xx int
declare @cntr int
set @cntr = 0
set @st = 1
select @en = CHARINDEX(@delimiter, @str, @st)
if @en = 0
set @en = LEN(@str)
while @en <= LEN(@str) and @cntr < 11 begin
set @cntr = @cntr + 1
set @xx = @en - @st
if @cntr = 1
insert into @output(t1) values(SUBSTRING(@str, @st, @xx))
if @cntr = 2
update @output set t2 = SUBSTRING(@str, @st, @xx)
if @cntr = 3
update @output set t3 = SUBSTRING(@str, @st, @xx)
if @cntr = 4
update @output set t4 = SUBSTRING(@str, @st, @xx)
if @cntr = 5
update @output set t5 = SUBSTRING(@str, @st, @xx)
if @cntr = 6
update @output set t6 = SUBSTRING(@str, @st, @xx)
if @cntr = 7
update @output set t7 = SUBSTRING(@str, @st, @xx)
if @cntr = 8
update @output set t8 = SUBSTRING(@str, @st, @xx)
if @cntr = 9
update @output set t9 = SUBSTRING(@str, @st, @xx)
if @cntr = 10
update @output set t10 = SUBSTRING(@str, @st, @xx)
set @st = @en + 1
if @st > len(@str)
begin
set @en = @en + 100
end
else
begin
select @en = CHARINDEX(@delimiter,@str, @st)
if @en = 0
begin
set @en = LEN(@str)
set @xx = @en - @st
end
end
end
return
end
/*
這將允許您通過分隔符分裂到10場了。您可以添加更多的,如果你的需求超過列表10
使用
select * from TableName a
cross apply splitStr(a.FiledName, ',')
*/
在SQL服務器 – Jade
玉無斯普利特()函數,我知道心不是我正在尋找一種能夠滿足我需要的功能或一些代碼來分割列的功能。 – user9969
不要試圖將*多個*數據項存儲在一個列中會好得多。 –