Parsing the comma separated values into a temporary table

(Works in both SQL Server 7.0 and 2000)

Declare @OrderList varchar(500)
set @OrderList = 'Order1,Order2,,Order3,,,Order4,Order5,';

drop TABLE #TempList

CREATE TABLE #TempList
(
   OrderID varchar(20)
)

DECLARE @OrderID varchar(10), @Pos int
SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
SET @Pos = CHARINDEX(',', @OrderList, 1)

IF REPLACE(@OrderList, ',', '') <> ''
BEGIN
   WHILE @Pos > 0
   BEGIN
       SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
       IF @OrderID <> ''
       BEGIN
           INSERT INTO #TempList (OrderID) VALUES (@OrderID)
       END
       SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
       SET @Pos = CHARINDEX(',', @OrderList, 1)
   END
END

SELECT * FROM #TempList t

+-+-+-+-+-+
OUTPUT
+-+-+-+-+-+

OrderID
----------
Order1
Order2
Order3
Order4
Order5

Comments

Popular posts from this blog

How to Update Dependent Excel Cells Automatically

Polymorphism in C#

MVC Request Execution Stages - Life Cycle

Variable Value in Top Statement

Auto Refresh .aspx page - ASP.NET

ASP.NET MVC Version History

Page Life Cycle in ASP.NET

Managed Code and UnManaged Code