Solved

SQL Loop Through Comma Separated Variable?

Posted on 2014-01-27
8
5,188 Views
Last Modified: 2014-01-29
I need to Update a table having dynamically created column names. I have the names in a comma-delimited @Columns variable, filled by a cursor during column creation. I don't know MS SQL can use a 'For' or 'Foreach' against a comma-delimited variable string.  I have some code below, it's missing the column-name-extraction syntax... Help

Note: columns names are 4-digit part numbers
Note: update appends a plus(+) to the column data which shows a price increase

Declare @ID = 1201
Declare @Columns      varchar(max) = '1495, 1579, 4578, 9147, 17493, 6482'
Declare @Column            varchar(30)
Declare @i      int = 1
Declare @Sql varchar(max)

While (@i < @Count)            
   Begin                  

       @Column = ??????

        Set @Sql  = 'Update a Set a.' + @Column + ' = ' + @Column + '' +''
                             + ' From #PartNumbers a
                            where ID = ' + CAST(@ID AS VARCHAR) ;
      Exec(@Sql);
   End                  
Set @i = @i + 1
End
0
Comment
Question by:WorknHardr
  • 3
  • 3
  • 2
8 Comments
 
LVL 16

Assisted Solution

by:Surendra Nath
Surendra Nath earned 250 total points
ID: 39813614
Hi

Inorder to accomplish this task, you first need to create a split function the code is pasted here for your convinience, if you want to know further about how this function works you can visit my blog here http://everysolution.wordpress.com/2011/07/28/udf-to-split-a-delimited-string-and-return-it-as-a-table/
 
Split Function

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
 DECLARE @index INT
 SET @index = Charindex(@SplitOn,@RowData)
 While (@index>0)
 Begin
 Insert Into @RtnValue (data)
  Select
 Data = ltrim(rtrim(Substring(@RowData,1,@index-1)))
 
 Set @RowData = Substring(@RowData,@index+1,len(@RowData))
 Set @Cnt = @Cnt + 1
 SET @index = Charindex(@SplitOn,@RowData)
 End
 
 Insert Into @RtnValue (data)
 Select Data = ltrim(rtrim(@RowData))
 
 Return
END

Open in new window



Re-writing your code

Declare @ID = 1201
Declare @Columns      varchar(max) = '1495, 1579, 4578, 9147, 17493, 6482'
Declare @Column            varchar(30)
Declare @i      int = 1
Declare @Sql varchar(max)
Declare @Data VARCHAR(10)

DECLARE @t TABLE
(
  Data VARCHAR(10)
)

INSERT INTO @T
SELECT DATA FROM dbo.Split(@Columns,',')

DECLARE T CURSOR FOR
SELECT Data From @t 

FETCH T INTO @Data

WHILE @@FETCH_STATUS = 0
BEGIN

Set @Sql  = 'Update a Set a.[' + @Data + '] = [' + @Data + ']' + '' +'' 
                    + ' From #PartNumbers a 
                  where ID = ' + CAST(@ID AS VARCHAR) ;
Exec(@Sql);
FETCH T INTO @Data
End                  

CLOSE T
DEALLOCATE T

Open in new window

0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 250 total points
ID: 39813629
Declare @ID int
Declare @Columns varchar(max)
Declare @Column varchar(30)
Declare @Column_End int
Declare @Sql varchar(max)

SET @ID = 1201
SET @Columns = '1495, 1579, 4578, 9147, 17493, 6482'

SET @Sql = 'UPDATE a
SET'

WHILE LEN(@Columns) > 0
BEGIN
    SET @Column_End = CHARINDEX(',', @Columns)
    IF @Column_End = 0
        SET @Column_End = LEN(@Columns) + 1
    SET @Column = LTRIM(RTRIM(LEFT(@Columns, @Column_End - 1)))
    SET @Sql = @Sql + ' a.[' + @Column + '] = [' + @Column + '] + ''+'','
    SET @Columns = SUBSTRING(@Columns, @Column_End + 1, 2000000000)
END --WHILE

SET @Sql = LEFT(@Sql, LEN(@Sql) - 1) + '
FROM dbo.tablename a
WHERE a.ID = ' + CAST(@ID AS varchar(10))

PRINT @Sql
--EXEC(@Sql)
0
 

Author Comment

by:WorknHardr
ID: 39818432
>>ScottPletcher

Q. Could your code be used a Function?
0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39818527
Not really.  It's custom code to match your stated requirements.   A function can't update a permanent table anyway.

I can give you code for a very high-performance splitter function that is an inline-table-valued function.  That's extremely good for splitting columns values from a table, where the function might have to be called thousands or millions of times.
0
 

Author Comment

by:WorknHardr
ID: 39818723
I'm updating a #Temp table and I like to use reusable Functions when ever possible.
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39818795
My earlier statement wasn't broad enough -- a SQL Server function can't update any table.

Reusing code for a temp table will be tricky even in a proc, but it could be done.
0
 
LVL 16

Expert Comment

by:Surendra Nath
ID: 39818799
@worknHardr -- did you consider using my solution as it seems it has a function that you might need
0
 

Author Closing Comment

by:WorknHardr
ID: 39819671
Both code examples are great, thx
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
convert in derived column 7 28
Need help on t-sql 2012 10 54
SQL Server Designer 19 40
Increment column based of a FK 8 21
When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question