October 11, 2012 at 5:26 am
Hi,
I have a column like this:
"Thing, Thing2, thing14, more things"
I would like to split it up using a view to be able to insert the data into a new table - Is there a function for selecting data and splitting it up using a comma delimiter?
Thanks
October 11, 2012 at 5:34 am
October 11, 2012 at 9:35 am
A little bit down in this post is one example and a link to something someone said is better.
http://www.sqlservercentral.com/Forums/Topic1366387-338-1.aspx
Here is the function in that link:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[DelimitedStringToTable](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
GO
October 11, 2012 at 9:53 am
tyson.price (10/11/2012)
A little bit down in this post is one example and a link to something someone said is better.http://www.sqlservercentral.com/Forums/Topic1366387-338-1.aspx
Here is the function in that link:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[DelimitedStringToTable](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
GO
Be careful now.... that's one of the slowest methods there is for splitting delimited strings. Please see the link that Phil (above) posted where he says "here" (that word is the link).
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply