Problem With Temp Table

  • Hello,

    Consider the following code;

    IF @MonthInputValue <> 'All'

      BEGIN

           SELECT * 

           INTO

              #months

           FROM

              dbo.fn_split(@MonthInputValue,',')

      

           UPDATE #months

           SET Value = dbo.fn_ConvertMonth(value)

      END

    ELSE

      BEGIN

         SELECT *

         INTO

              #months

         FROM

              dbo.fn_GetAllMonths()

      END

    END

    *********************

    When I try to implement this into the proc I'm creating I get an error message that states the following;

    There is already an object named '#months' in the database

    If this is a temp table, why would I get this message? When I try to drop the temp table, I get a message that the table does not exist.

    Any ideas?

    Thank you for your help!

    CSDunn

  • Before you do a SELECT INTO its a good idea to check if the table exists in the tempdb and drop it first. You prbly have an object left out from previous run that hasnt yet been cleaned. so you have to do the clean up yourself.

    ******************
    Dinakar Nethi
    Life is short. Enjoy it.
    ******************

  • T-SQL is parsed.

    Then it is executed.

    The parsing step doesn't deal with the fact that your 2 SELECT INTO's are in mutually exclusive conditional blocks, so it throws the error at parse time thinking you're doing 2 SELECT INTO's on the same tablename.

    Use CREATE TABLE #Months to create the table *before* the IF .. statement, and then INSERT INTO it.

  • Thank you for your help!

    CSDunn

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

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