• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 561
  • Last Modified:

tsql to Parse a comma delimited list

I need to parse a comma delimited list in a stored procedure and Insert the parsed values into a table.

I copied from the following reference:

http://www.sqlbook.com/SQL/Parse-a-comma-delimited-list-8.aspx

The query ran but did not insert the parsed substring into a table.
The actual insert statement was not included in the article.

-- in the real world you would now do something with the list item
       -- * inserting it into a table

This is my stored proc:
  ALTER PROCEDURE [dbo].[usp_getEODExtract]
AS
DECLARE @List nvarchar(100)
DECLARE @ListItem nvarchar(10)  
DECLARE @Pos int

SET @List = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

-- Loop while the list string still holds one or more characters
WHILE LEN(@List) > 0
Begin
       -- Get the position of the first comma (returns 0 if no commas left in string)
       SET @Pos = CHARINDEX(',', @List)

       -- Extract the list item string
       IF @Pos = 0
       Begin
               SET @ListItem = @List
       End
       ELSE
       Begin
               SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
       End
--http://www.sqlbook.com/SQL/Parse-a-comma-delimited-list-8.aspx
       -- in the real world you would now do something with the list item
       -- * inserting it into a table
       -- * using it as a parameter in a stored procedure call
       -- * parsing it into a numeric / datetime format to use in a calculation
       -- etc....
      INSERT INTO StockDataWork (SymbolName) Values(@ListItem)
       -- remove the list item (and trailing comma if present) from the list string
       IF @Pos = 0
       Begin
               SET @List = ''
       End
       ELSE
       Begin
               -- start substring at the character after the first comma
                SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
       End
       
       
End

After execution: Command(s) completed successfully.

SELECT * FROM StockDataWork returned 0 rows.

 INSERT INTO StockDataWork (SymbolName) Values('abc') works

What do I need to change?

Thanks
0
Dovberman
Asked:
Dovberman
4 Solutions
 
tigin44Commented:
your procedure works correct.. no error exists. I tried and inserted all the values to the table.  Make sure you are working an the same database, I mean the procedure and the table you are querying are the same objects you are referencing.
0
 
Habib PourfardSoftware DeveloperCommented:
Try the following code:
DECLARE @List VARCHAR(8000), @Sql VARCHAR(MAX) 

SET @List = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

CREATE TABLE #TempListTable ( [Value] VARCHAR(128) )

SELECT  @Sql = 'INSERT INTO #TempListTable ([Value]) Values (''' + REPLACE(@List, ',', '''),(''') + ''')'
EXEC (@Sql)

INSERT INTO StockDataWork (SymbolName) 
SELECT [Value] FROM #TempListTable

IF OBJECT_ID('tempdb..#TempListTable') IS NOT NULL DROP TABLE #TempListTable

Open in new window

0
 
pateljituCommented:
As mentioned by @tigin44 your store procedure is working as expected.

How are you executing your store procedure i.e. are you trying via SQL management console or code.

As I tried executing SP from t-sql exec usp_getEODExtract and after execution I get output "(1 row(s) affected)" [8 times for each comma seperated value].

Confirm if you have proper permission is executing store procedure from code.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
DovbermanAuthor Commented:
tigin44

This is my entire sp:

USE [stockprosql]
GO
/****** Object:  StoredProcedure [dbo].[usp_getEODExtract]    Script Date: 01/03/2014 09:46:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:            <Author,,Name>
-- Create date: <Create Date,,>
-- Description:      Appends to the end of day SQL Server work table from
--                        the downloaded end of day text table
--
-- =============================================
ALTER PROCEDURE [dbo].[usp_getEODExtract]
AS
declare @ListSymbolName VARCHAR(MAX)
declare @ListOpenPrice VARCHAR(MAX)
DECLARE @List nvarchar(100)
DECLARE @ListItem nvarchar(10)  
DECLARE @Pos int
DECLARE @ListItem1 nvarchar(10)  


--set @ListSymbolName = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

SET @List = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

-- Loop while the list string still holds one or more characters
WHILE LEN(@List) > 0
Begin
       -- Get the position of the first comma (returns 0 if no commas left in string)
       SET @Pos = CHARINDEX(',', @List)

       -- Extract the list item string
       IF @Pos = 0
       Begin
               SET @ListItem = @List
       End
       ELSE
       Begin
               SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
       End
--http://www.sqlbook.com/SQL/Parse-a-comma-delimited-list-8.aspx
       -- in the real world you would now do something with the list item
       -- * inserting it into a table
       -- * using it as a parameter in a stored procedure call
       -- * parsing it into a numeric / datetime format to use in a calculation
       -- etc....
     
       -- remove the list item (and trailing comma if present) from the list string
       IF @Pos = 0
       Begin
               SET @List = ''
       End
       ELSE
       Begin
               -- start substring at the character after the first comma
                SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
       End
       
End

What did you change to make it work?

Thanks
0
 
DovbermanAuthor Commented:
pourfard,

Your solution is simple and it worked for me.
0
 
DovbermanAuthor Commented:
pateljitu,

Where did you place the INSERT INTO Statement?

Thanks,
0
 
pateljituCommented:
Insert statement is within your store procedure so basically when you execute this t-sql line exec usp_getEODExtract in SQL management studio it will take care loop through the comma separated values and insert the same in database table.
0
 
DovbermanAuthor Commented:
notice that the Insert statement was removed from the stored procedure during many  failed editing attempts.

Where should I now replace it?

Thanks
0
 
DovbermanAuthor Commented:
pourfard,

Suppose I need to insert two columns.

DECLARE @List VARCHAR(8000), @ListPrice VARCHAR(8000), @Sql VARCHAR(MAX)

SET @List = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'
SET @ListPrice = '27.1,24.5,12.3,34.5,67.1,74.2,37.1,12.8'

-- For 1 column as you stated:

SELECT  @Sql =
'INSERT INTO #TempListTable ([Value]) Values (''' + REPLACE(@List, ',', '''),(''') + ''')'

What would the statement be for inserting the @List value and @ListPrice value ?

Thanks,
0
 
pateljituCommented:
Your SP should look as code below with insert statement:

-- =============================================
-- Author:            <Author,,Name>
-- Create date: <Create Date,,>
-- Description:      Appends to the end of day SQL Server work table from
--                        the downloaded end of day text table
-- 
-- =============================================
ALTER PROCEDURE [dbo].[usp_getEODExtract]
AS
declare @ListSymbolName VARCHAR(MAX)
declare @ListOpenPrice VARCHAR(MAX)
DECLARE @List nvarchar(100)
DECLARE @ListItem nvarchar(10)  
DECLARE @Pos int
DECLARE @ListItem1 nvarchar(10)  


--set @ListSymbolName = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

SET @List = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

-- Loop while the list string still holds one or more characters
WHILE LEN(@List) > 0
Begin
       -- Get the position of the first comma (returns 0 if no commas left in string)
       SET @Pos = CHARINDEX(',', @List)

       -- Extract the list item string
       IF @Pos = 0
       Begin
               SET @ListItem = @List
       End
       ELSE
       Begin
               SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
       End
	   --http://www.sqlbook.com/SQL/Parse-a-comma-delimited-list-8.aspx
       -- in the real world you would now do something with the list item
       -- * inserting it into a table
       -- * using it as a parameter in a stored procedure call
       -- * parsing it into a numeric / datetime format to use in a calculation
       -- etc....
		
      INSERT INTO testing (Name) values(@ListItem)
       -- remove the list item (and trailing comma if present) from the list string
       IF @Pos = 0
       Begin
               SET @List = ''
       End
       ELSE
       Begin
               -- start substring at the character after the first comma
                SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
       End
       
End

Open in new window

0
 
DovbermanAuthor Commented:
pateljitu,

Thank you.

The actual delimited string has 1800 values.

Will performance be affected?
0
 
DovbermanAuthor Commented:
Thanks to everyone
0
 
pateljituCommented:
With 1800 values performance would not be affected much (total execution should be done in 2 seconds), only change in your SP would be from declaration DECLARE @List nvarchar(100) to DECLARE @List nvarchar(MAX).

But if delimited string value increases to 4000+, performance will have issues.
0
 
DovbermanAuthor Commented:
Yes, Execution time for 1800 rows is 2 seconds.  Another sample with 3200 rows is about 3 seconds.  The max file I will process is about 3200 rows.

Thanks,
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now