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

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
ScuzzyJoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lcohanDatabase AnalystCommented:
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.
0
Éric MoreauSenior .Net ConsultantCommented:
you will need to use dynamic SQL (concatenate a string and then execute it): https://msdn.microsoft.com/en-us/library/ms188001.aspx
0
ScuzzyJoAuthor Commented:
Hi Icohan

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

Thanks
Sarah
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

ScuzzyJoAuthor Commented:
Hi Éric

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

Sarah
0
lcohanDatabase AnalystCommented:
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
0
ScuzzyJoAuthor 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
0
Scott PletcherSenior DBACommented:
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)
0
Pawan KumarDatabase ExpertCommented:
@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 !
0
ScuzzyJoAuthor 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
0
ScuzzyJoAuthor 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
0
ScuzzyJoAuthor 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
0
Pawan KumarDatabase ExpertCommented:
@ScuzzyJo - Excellent attitude. One you fight and do it yourself, you will learn and grow.
0
lcohanDatabase AnalystCommented:
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
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ScuzzyJoAuthor 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
0
ScuzzyJoAuthor 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
0
ScuzzyJoAuthor 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.
0
lcohanDatabase AnalystCommented:
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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.