Check if a temporary table exists and delete if it exists before creating a temporary table

前端 未结 15 601
忘掉有多难
忘掉有多难 2020-11-29 14:13

I am using the following code to check if the temporary table exists and drop the table if it exists before creating again. It works fine as long as I don\'t change the colu

相关标签:
15条回答
  • 2020-11-29 15:06

    Yes, "invalid column" this error raised from the line "select company, stepid, fieldid, NewColumn from #Results".

    There are two phases of runing t-sql,

    first, parsing, in this phase the sql server check the correction of you submited sql string, including column of table, and optimized your query for fastest retreival.

    second, running, retreiving the datas.

    If table #Results exists then parsing process will check the columns you specified are valid or not, else (table doesn't exist) parsing will be by passsed the checking columns as you specified.

    0 讨论(0)
  • 2020-11-29 15:11

    The statement should be of the order

    1. Alter statement for the table
    2. GO
    3. Select statement.

    Without 'GO' in between, the whole thing will be considered as one single script and when the select statement looks for the column,it won't be found.

    With 'GO' , it will consider the part of the script up to 'GO' as one single batch and will execute before getting into the query after 'GO'.

    0 讨论(0)
  • 2020-11-29 15:11

    Now you can use the below syntax if you are using one of the new versions of SQL Server (2016+).

    DROP TABLE IF EXISTS schema.yourtable(even temporary tables #...)
    
    0 讨论(0)
提交回复
热议问题