Link to home
Start Free TrialLog in
Avatar of jjliu4492
jjliu4492

asked on

How to use substring to split a string value

I have a string value, that I want to separate into 6 strings. The delimiter is _. So for this string, the six values would be: How would I go about splitting the string in SQL Server 2008?

TAMPA, FL_VASTEC__ACCESSIBILITY TRAINING_508_FIRST

TAMPA, FL
VASTEC
null
ACCESSIBILITY TRAINING
508
FIRST
Avatar of kaminda
kaminda
Flag of Sri Lanka image

You can use the below function. Call it by passing the string value and the delimiter. It will return a table with splitted values as rows.
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

Open in new window

Avatar of Guy Hengel [angelIII / a3]
it depends a bit what you want to do with the values ...
I also wrote an article about this kind of thing: https://www.experts-exchange.com/A_1536.html
ASKER CERTIFIED SOLUTION
Avatar of RGBDart
RGBDart
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jjliu4492
jjliu4492

ASKER

I am trying to split up the field, and save the split values into a new table. Can I do this without using a function, and just use substring?
>Can I do this without using a function, and just use substring?
not really. technically yes, but you will multiply the instr() and substring functions...
select * from dbo.fnSplit('TAMPA, FL_VASTEC__ACCESSIBILITY TRAINING_508_FIRST', '_')

Can I have it display as one row, with each field as a column?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If I use fnSplit, my result set is:

How can I get a specific row value? For example, I need to insert "VASTEC" into a column in my database.

item
TAMPA, FL
VASTEC
NULL
ACCESSIBILITY TRAINING
508
FIRST

please see my comment above.
What is your code for dbo.ParmsToList?
it's in the article I linked above