About Me

My photo
a Dynamic and Energetic guy.....

Tuesday, February 2, 2010

String Split in SQL

Declare @checkedItems varchar(20)

SET @checkedItems ='N,L,D,E'

Declare
@ParsedList table
(
OrderID varchar
)

DECLARE @OrderID varchar(10), @Pos int

SET @checkedItems = LTRIM(RTRIM(@checkedItems))+ ','
SET @Pos = CHARINDEX(',', @checkedItems, 1)

IF REPLACE(@checkedItems, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @OrderID = LTRIM(RTRIM(LEFT(@checkedItems, @Pos - 1)))
IF @OrderID <> ''
BEGIN
INSERT INTO @ParsedList (OrderID)
VALUES (CAST(@OrderID AS varchar)) --Use Appropriate conversion
END
SET @checkedItems = RIGHT(@checkedItems, LEN(@checkedItems) - @Pos)
SET @Pos = CHARINDEX(',', @checkedItems, 1)

END
END

select * from @ParsedList

====================================
OUTPUT
====================================
OrderID
N
L
D
E

No comments:

My Masters