Parsing Comma Delemeted String in Sql

9:46 PM
I will just go with the Example as its Self Exclamatory.

Sql Query:
declare @string varchar(500)
set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

declare @pos INT
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn’t exist
if right(rtrim(@string),1) <> ','
 set @string = @string  + ','

set @pos =  patindex('%,%' , @string)
while @pos <> 0
begin
 set @piece = left(@string, @pos - 1)
 
 -- You have a piece of data, so insert it, print it, do whatever you want to with it.
 print cast(@piece as varchar(500))

 set @string = stuff(@string, 1, @pos, '')
 set @pos =  patindex('%,%' , @string)
end

Output:






1 comments:

{ Lucy } at: June 24, 2012 at 8:15 PM said...

I like to make friends with you,haha.


----------------------------------------------------------------------------------------------------------------------------------------
Rc Helicopter|Mini Rc Helicopter|Rc Helicopters

Post a Comment