How to split comma separated string in sql server
this is the function i found after some Googling.
Which Tekes Two Arguments and Returns A table which contains all Values separated by comma in a Column of table.
(1)String Separated With some character.
(2)characted from where to split string.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitString]
(
@StringToSplit nvarchar(2000),
@SplitFrom nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitFrom,@StringToSplit)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@StringToSplit,1,Charindex(@SplitFrom,@StringToSplit)-1)))
Set @StringToSplit = Substring(@StringToSplit,Charindex(@SplitFrom,@StringToSplit)+1,len(@StringToSplit))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@StringToSplit))
Return
END
How To Call:
After CReating this function We can call it like a table.
select * from [dbo].[SplitString]('a,b,c',',')
you can Find More Details on
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648
Thanks.
A blog where you can find tutorials on ASP.Net, Ajax Control Toolkit, SQL Server 2008/2005, WCF, WPF, Silverlight, Azure and other Microsoft Technologies
Friday, April 17, 2009
1 comment:
Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author
Subscribe to:
Post Comments (Atom)
Hi thank you very much.
ReplyDeleteThis sql function helps me a lot.
Thank you again!!
Chamara
(SriLanka)