65.9K
CodeProject is changing. Read more.
Home

Updating a temp table in a Stored Proc

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (1 vote)

Oct 24, 2011

CPOL
viewsIcon

20342

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:

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:

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.