Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Updating a temp table in a Stored Proc

1.00/5 (1 vote)
1 Nov 2011CPOL 20.3K  
How to update the schema of a temp table in a Stored Procedure in SQL Server

Well, I just spent twenty/thirty minutes realising that when you change the definition of a temporary table being used in an SQL Server Stored Procedure, you need to actually delete the temp table before you can recompile the procedure. So, something like:


SQL
IF OBJECT_ID(N'tempdb..#tableName', N'U') IS NOT NULL DROP TABLE #tableName;
CREATE TABLE #tableName(
    Key1        INT
,   Description NVARCHAR(255)
)   
/* do stuff with table */

And then change it to:


SQL
IF OBJECT_ID(N'tempdb..#tableName', N'U') IS NOT NULL DROP TABLE #tableName;
CREATE TABLE #tableName(
    Key1        INT
,   Key2        INT
,   Description NVARCHAR(255)
,   AggAmount   FLOAT
)   
/* do stuff with table referencing agg amount column*/

Then the table definition won't update when you change it in code without dropping the stored definition. You can highlight the drop statement and run that by itself, and then it'll recompile your code.


Simple, but easy to miss.


Hope I saved somebody a little hair-pulling.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)