Question: What is a temporary stored procedure? A SQL Server procedure named with a leading # is local to its creating connection. It lives in TempDB and disappears when that connection closes, without waiting for a server restart.

During a Comprehensive Database Performance Health Check, I often compare alternative versions of a procedure. Naming permanent copies Temp, Temp2 and TempFinal quickly leaves a database full of experiments. A local temporary procedure keeps a short, single-session comparison out of the application’s permanent procedure list.
Create and Execute It in the Same Connection
CREATE PROCEDURE #TempSP
AS
SELECT 1 AS SPName;
GO
EXEC #TempSP;
GOThe result is one column named SPName, containing 1. CREATE PROCEDURE starts its own batch; GO is the client batch separator. Reconnecting the query window creates a new connection, so the earlier local temporary procedure won’t be there.
What Changes With Two Hash Signs?
-- Concept only: use a unique name in a shared instance.
CREATE PROCEDURE ##GlobalSP
AS
SELECT 1 AS SPName;
GOA global temporary procedure can be accessed from other connections. Its lifecycle depends on the sessions using it, so don’t promise that it remains until the server restarts. Shared names also mean collisions and unintended callers. For a private tuning experiment, I prefer the local form.
Neither form makes a test representative automatically. Keep parameters, data and session SET options comparable when evaluating plans. Once an alternative is ready for application use, deploy a reviewed permanent procedure through the normal process; a temporary object is not an application deployment strategy.

A temporary procedure is not a shortcut to production, it is a scratch pad, and it vanishes with your connection.
Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.
Discover more from SQL Authority with Pinal Dave
Subscribe to get the latest posts sent to your email.





2 Comments. Leave new
Your explanation about the lifetime of these procedures are incorrect. Both procedures exists until the session is gone, not after a restart. If you want to create a procedure until the server reboots, create it directly in tempdb
Your Point is very correct. Let me update the blog post to reflect that. I appreciate your time.