Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a temporary table like a current table in SQL Server 2005/2008

How do you create a temporary table exactly like a current table in a stored procedure?

like image 855
craigmoliver Avatar asked Nov 06 '09 19:11

craigmoliver


People also ask

How do I create a temporary table in SQL Server?

Create a Global Temporary Table in SQL Server. You can also create a global temporary table by placing double hash (##) before the temporary table name. The global temporary table will be available across different connections. 3 records will be inserted into the table.

How do I create a temp table in SQL query?

To create a temporary table, you must have the CREATE TEMPORARY TABLES privilege. After a session has created a temporary table, the server performs no further privilege checks on the table. The creating session can perform any operation on the table, such as DROP TABLE , INSERT , UPDATE , or SELECT .

What is the alternative for temporary table in SQL Server?

A valuable alternatives for the SQL temp table and table variable are SCHEMA_ONLY Memory-Optimized tables and the Memory-optimized Table Variable, where the data will be completely stored in the memory without the need to touch the TempDB database, providing the best data access performance.


2 Answers

select * into #temp_table from current_table_in_stored_procedure

#temp_table - locally temp
##temp_table - globally temp

select top 0 * into #temp_table from current_table_in_stored_procedure to have empty table
like image 107
LukLed Avatar answered Oct 05 '22 13:10

LukLed


SELECT * INTO #t FROM table

if you want it to be empty:

SELECT * INTO #t FROM table WHERE 1 = 2

like image 38
manji Avatar answered Oct 05 '22 13:10

manji