Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL Loop Through Comma Separated Variable?

Posted on 2014-01-27
8
Medium Priority
?
6,858 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 16

Assisted Solution

by:Surendra Nath
Surendra Nath earned 1000 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 70

Accepted Solution

by:
Scott Pletcher earned 1000 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
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
LVL 70

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 70

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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

636 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