Temporary Tables and Table Variables Flashcards
Create a temporary table based on the schema of an existing table
SELECT [COLUMNS] INTO #TEMPTABLE WHERE 1 = 0
Does a temporary table exist after database disconnection?
No
Find the name of a temporary table that you can then search for in the sys.objects view
use tempdb
exec sp_help #temptable
What happens if you create a temporary table with the same name in a different session?
It gives the temp table a unique name in the tempdb
Can you use user data types in a temp table?
No
What is the workaround to use user data types in temp tables?
Create the user data type in Tempdb
Create a temp table using dynamic SQL then select from it within your session. Does that work?
The temp table will be created, but you can’t use it within the session scope.
If you include the insert and select from within your dynamic SQL, that will work.
Can you create your temp table in a session then use dynamic SQL to insert into it?
Yes
How can you make a temporary table global?
add a second #:
create table ##temptable
Can you create two global temp tables with the same name in two different sessions?
No, you will get an error that the object already exists
What happens if you try to create two global temp tables with the same name in two different databases and sessions?
You will get the error that the object already exists.
Will a temporary table that is created in a stored procedure be available to use within the same session?
No, as soon as the stored procedure is done executing, the temp table is dropped.
Create a stored procedure that creates a temp table and then calls another stored procedure that inserts into the table and selects from it. Does it work?
Yes, both procedures will be able to access the same temporary table.
Can you create a view based on a temp table?
No
Can you reference a temp table within a table trigger?
Yes
Can you reference a temp table within a function?
No.
When you create a temp table from a database, where does it’s collation come from?
Tempdb
What constraints work within a temporary table?
Default
Check
Primary Key
Are Foreign Key constraints available for temp tables?
No
Can you use indexes with temp tables?
Yes, both clustered and nonclustered indexes work.
Can you use identity columns with a temp table?
yes
How does a temp table behave with regard to implicit and explicit transactions?
Exactly the same as with a permanent table: rollbacks will remove records that haven’t been committed.
How do statistics work for temporary tables?
Exactly the same as with permanent table: stats are auto generated based on queries and are updated regularly.