SQL How to add a variable name as part of a new column name

ScuzzyJo
ScuzzyJo used Ask the Experts™
on
Hi

I hope someone can help me with this.  I have a table in which I need to add new columns.  The data is dynamic and the number of columns I have to add will depend on a count of some other data.  I've got that count and have, so far, written but not tested this:

SELECT @maxoldSSN = max(cnt) FROM LFRD_Old_SSN_Counter;
SET @countoldSNN = 0;
--
WHILE @countoldSNN < @maxoldSSN
BEGIN
      ALTER TABLE LFRD
      ADD old_SSN varchar (15);
      SET @countoldSNN = @countoldSNN + 1
END

My question is how do I add the count part into the new column names?  I want them to be old_SSN1, oldSSN2 and so on.  I realise I can use the value in @countoldSSN but don't know how to concatenate it into a column name.

Hopefully, this won't be too difficult :-).

As an aside, and I hope it's OK to ask this as part of my question, when I had 2012, I had a watch window so that I could see the variables changing when I stepped through.  I can't find that in 2014!  I have looked it up but I don't have the options under the menus that Microsoft seem to think I should.  Does anyone know how to get this to show?

Thanks in advance for your help.

Sarah
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
lcohanDatabase Analyst

Commented:
You can use dynamic SQL to build the string that will be executed to add the actual column names and you can use the "magic" sysname SQL own datatype for the variable containing the count.
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
you will need to use dynamic SQL (concatenate a string and then execute it): https://msdn.microsoft.com/en-us/library/ms188001.aspx

Author

Commented:
Hi Icohan

Thanks for the comment, but it's gone straight over my head!  How do I do any of that?

Thanks
Sarah
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
Hi Éric

Thanks.  I'm looking it up now to try to understand how it works.

Sarah
lcohanDatabase Analyst

Commented:
So please run script below and note it will not change anything but just PRINT commands to be executed later - hope that's what you mean:

declare @maxcnt int;
declare @crtcnt sysname;
declare @sqlstr varchar(max);

--set @maxcnt = SELECT count(*) FROM LFRD_Old_SSN_Counter;
set @maxcnt = 10;


WHILE @maxcnt > 0
BEGIN
      SET @crtcnt = @maxcnt;
      SET @sqlstr = 'ALTER TABLE LFRD ADD old_SSN' + @crtcnt + ' varchar (15);'
      PRINT @sqlstr;
      --EXEC @sqlstr;
      SET @maxcnt = @maxcnt - 1;
END

Author

Commented:
Hi Icohan

Thanks for this.  I'm working through it so that I understand it but will carry on tomorrow as it's nearly 6:00 pm here (UK).

Thanks
Sarah
Scott PletcherSenior DBA
Most Valuable Expert 2018
Top Expert 2014

Commented:
Modern coding preference is to avoid loops.  Typically FOR XML is used to concat in SQL while avoiding looping:

DECLARE @maxoldSSN int;
DECLARE @sql varchar(8000)

SELECT @maxoldSSN = MAX(cnt) FROM LFRD_Old_SSN_Counter;

;WITH
cteTally10 AS (
    SELECT * FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) numbers(number)
),
cteTally100 AS (
    SELECT ROW_NUMBER() OVER(ORDER BY c1.number) AS number
    FROM cteTally10 c1
    CROSS JOIN cteTally10 c2
)
SELECT @sql = STUFF((
    SELECT ',oldSSN' + CAST(t.number AS varchar(4)) + ' varchar(15)'
    FROM cteTally100 t
    WHERE t.number BETWEEN 1 AND @maxoldSSN
    FOR XML PATH('')
    ), 1, 1, '')

SET @sql = 'ALTER TABLE dbo.LFRD ADD ' + @sql + ';'
PRINT @sql
EXEC(@sql)
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
@Author - Is your task completed ? Do you need more help with this ? If yes please let me know. Shall write the complete script for you !

Author

Commented:
Hi Scott

Thanks for your post.  I appreciate what you're saying but, at the moment, I'm struggling to understand it as you've used terms and logic that I haven't come across before.

When I'm more advanced, I'll look back at it and try to avoid loops but, for now, it's not my main concern and adds to my confusion.

Thanks
Sarah

Author

Commented:
Hi Pawan

I'm just starting back on this today.  Thanks for your offer.  I might well take you up on understanding it, but I'd rather write it myself or I won't learn.

Thanks
Sarah

Author

Commented:
Hi Icohan

I've worked through that it works fine.  I don't want to just print it though.  I want to actually add the columns into the LFRD table.  I've tried adapting it myself, but it didn't work.

Thanks
Sarah
Pawan KumarDatabase Expert
Awarded 2016
Top Expert 2016

Commented:
@ScuzzyJo - Excellent attitude. One you fight and do it yourself, you will learn and grow.
Database Analyst
Commented:
All you need now is to comment the print commands and uncomment the EXEC line so it will actualy perform the action like this:


declare @maxcnt int;
declare @crtcnt sysname;
declare @sqlstr varchar(max);

--you need to put the actual statement here that returns the MAX number of columns to be added
set @maxcnt = (SELECT count(*) FROM LFRD_Old_SSN_Counter);



WHILE @maxcnt > 0
BEGIN
      SET @crtcnt = @maxcnt;
      SET @sqlstr = 'ALTER TABLE LFRD ADD old_SSN' + @crtcnt + ' varchar (15);'
      --PRINT @sqlstr;
      EXEC @sqlstr;
      SET @maxcnt = @maxcnt - 1;
END

Author

Commented:
Hi Icohan

That's what I tried, among other things, but it didn't work.  It said it couldn't find the stored procedure:

Msg 2812, Level 16, State 62, Line 118
Could not find stored procedure 'ALTER TABLE LFRD ADD old_SSN1 varchar (15);'.

I understand why this should work but have no idea why it doesn't.

Thanks
Sarah

Author

Commented:
Hi Icohan

Thanks for all your help.  I've got it working.  I needed some brackets so that:

EXEC @sqlstr;

needed to be:

  EXEC (@sqlstr);

Thanks
Sarah

Author

Commented:
The solution needed some extra brackets but, other than that, works fine.  This is great as I've now learned how to do something else which, I think will be very, very useful in the future.
lcohanDatabase Analyst

Commented:
Sorry I missed those and I'm glad you learned something. That PRINT command is extremely useful to "debug" any SQL dynamic code before actually executing it.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial