Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i split a string from database field value....
Posted

 
Share this answer
 
Comments
Nik's Sangani 28-Feb-13 0:13am    
but i want to use table field... in that i have a string,...
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
i want to use field name not a string like='abc,def,fgh'
You can create a function to split the strings. Try the following function:
SQL
CREATE FUNCTION dbo.Split
(
	@RowData nvarchar(2000),
	@SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
	Id int identity(1,1),
	Data nvarchar(100)
) 
AS  
BEGIN 
	Declare @Cnt int
	Set @Cnt = 1

	While (Charindex(@SplitOn,@RowData)>0)
	Begin
		Insert Into @RtnValue (data)
		Select 
			Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

		Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
		Set @Cnt = @Cnt + 1
	End
	
	Insert Into @RtnValue (data)
	Select Data = ltrim(rtrim(@RowData))

	Return
END


Original Source : Here[^].


--Amit
 
Share this answer
 
Comments
Nik's Sangani 28-Feb-13 0:13am    
but i want to use table field... in that i have a string,...
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
i want to use field name not a string like='abc,def,fgh'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900