Temporary tables are a useful feature in SQL Server that allow you to store result sets temporarily for a given connection. They can be used like permanent tables but are automatically dropped when the connection is closed.
In SQL Server, temporary tables are created using the CREATE TABLE statement with the # or ## prefix. The # prefix creates a local temporary table that is only accessible within the current session, while the ## prefix creates a global temporary table that is accessible to all sessions.
Here’s an example of creating a local temporary table:
CREATE TABLE #Temp (
id INT
);
To view the column names of a temporary table, you can use the sp_columns system stored procedure:
EXEC sp_columns '#Temp';
Temporary tables in SQL Server are stored in the tempdb database. They are typically stored in disk, but if the data size is small, they may be stored in memory for faster access.
Unlike MySQL, SQL Server allows you to find temporary tables using the sys.tables system view in the tempdb database. This can be useful for troubleshooting or monitoring purposes.
It’s important to note that you can create a permanent table with the same name as a temporary table in the same connection. However, the structure of the permanent table will only be visible if the temporary table with the same name is dropped.
To drop a temporary table, you can use the DROP TABLE statement:
DROP TABLE #Temp;
After dropping the temporary table, you can still access the structure of the permanent table with the same name.
In summary, temporary tables in SQL Server provide a convenient way to store and manipulate result sets temporarily. They are especially useful in scenarios where you need to perform complex calculations or intermediate data processing within a single connection.