How to add add columns in a SP and reference them in the same SP?

  • Hi All,

    This might be a basic thing i am overlooking but i have a Stored procedure in which i have some

    ALTER TABLE myTable add col1 int

    ALTER TABLE myTable add col2 int

    statements. I then use a insert statement right after the alter statements but i get a Col1 not found error. If i put a GO after the ALTER table statements, my variables declared at the start go out of scope.

    What's a workaround for this?

    Thanks

  • May I ask for the business reason for that requirement?

    It sounds like a denormalized table (e.g. a monthly summary table with one column per month...)...



    Lutz
    A pessimist is an optimist with experience.

    How to get fast answers to your question[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]

  • Its nothing complicated, simply a previous developer left code which i am converting to a stored proc. it has 2 parts and not all fields can be present during the first part. i could simply create a separate table before the stored proc but i thought i'd ask if its simply a basic thing i am overlooking or is it a bad coding principle to do so

  • It could be done with a little dynamic SQL provided that either the dynamic SQL was protected from SQL Injection or simply had nothing to do with any external parameters.

    But, I have to agree... adding columns to a table in a stored procedure usually isn't the best idea. If you told us a bit more about why that's necessary, someone might be able to come up with a work around for you.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • You can use this

    EXEC sp_executesql N'ALTER TABLE myTable add col1 int'

    but a better solution would be to modify the "part 1" code so you don't need to do this.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply