Search code examples
sql-servert-sqlstored-procedurestemp-tables

Temporary Tables in SQL Server created and used inside a stored procedure


I'm creating a temporary table in a stored procedure. I understand that they get created and destroyed for each session, however something is not clear. Let's say two users access the web page where I call the stored procedure that creates the temporary table, would there be a conflict when the two users create the same temp table?

Thanks


Solution

  • Temporary tables are created per SQL connection so two users calling the same stored procedure would create an individual instance of the table in question.

    The simplest way to demonstrate this is to run the following query in 2 seperate query windows:

    select 1 as someid
    into #temp
    

    Each window will have it's own connection, so will create a unique temp table.

    If you look in System Databases > TempDB > Temporary Tables (you may have to refresh the table list), you will see 2 tables uniquely named, something like:

    #temp________xxx1
    #temp________xxx2
    

    If you then close one of the query windows and refresh the temp table list, you will see one table has been dropped.