views:

201

answers:

3

How can I create two temporary tables with the same structure without write twice?

Something like that:

DECLARE @TEST_TABLE1, @TEST_TABLE2 TABLE
(
    FIELD1 INT,
    FIELD2 INT
)

and NO:

DECLARE @TEST_TABLE1 TABLE
(
    FIELD1 INT,
    FIELD2 INT
)

DECLARE @TEST_TABLE2 TABLE
(
    FIELD1 INT,
    FIELD2 INT
)
A: 

The only very non-standard way I can think this may work is to just write to the sys.tables directly, but you would still have to do two inserts, but you are doing the tables at the same time.

That may not be what you want, but short of using a stored procedure, and making one call from your app, and two on the database I can't think of any other solution.

James Black
+5  A: 

These are not "temp tables", a temp table is CREATE TABLE #TempTable(x int)

to make this work for true table tables, try:

CREATE TABLE #TempTable(x int)
insert into #TempTable values(5) --test data to show no data copied to new table
select * into #tempTable2 from #TempTable where 1=2
select * from #TempTable
select * from #TempTable2

These are table vaiables (@tableVariable) and you have to declare each variable, there is no way around it.

KM
OK, you're right (about the definition for temp tables), and if there's no way, no problem. I think that variable tables are temporary, anyway. Tks.
Zanoni
A: 

Create the first temp table, then select into a second temp table:

-- Create first temp table

CREATE TABLE #TEST_TABLE1 ( FIELD1 int ,FIELD2 int )

-- Select into second temp table

SELECT * INTO #TEST_TABLE2 FROM #TEST_TABLE1

-- Vet existence of both temp tables

SELECT * FROM #TEST_TABLE1

SELECT * FROM #TEST_TABLE2

Yoav
with this code, you are going to copy all data from the #TEST_TABLE1 into #TEST_TABLE2
KM
KM, no you aren't because you haven't copied the data into #test_table1 yet.
HLGEM