Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare two table variables with identical structures?

I have the following table variable declaration:

DECLARE @MyTable TABLE
(
   --ten columns declared here
)

and I want to declare another table variable with identical structure (so that I insert-from-select into the first one and then copy the result into the second one and then I delete entries from the first variable one by one and return the second one as a result).

I tried this:

DECLARE @MyTable, @MyTableCopy TABLE
(
   --ten columns declared here
)

but SQL Server Express is not happy and says

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ','.

How do I declare two identically structured table variables?

like image 802
sharptooth Avatar asked Dec 18 '13 12:12

sharptooth


People also ask

Can a same constraint be used in 2 tables?

Yes you can do this from this example i didn't test it, but it should work.

Which is the correct way to DECLARE a table variable?

Syntax. If we want to declare a table variable, we have to start the DECLARE statement which is similar to local variables. The name of the local variable must start with at(@) sign. The TABLE keyword specifies that this variable is a table variable.

What is #temp table and @table variable in SQL Server?

Temp table: A Temp table is easy to create and back up data. Table variable: But the table variable involves the effort when we usually create the normal tables. Temp table: Temp table result can be used by multiple users. Table variable: But the table variable can be used by the current user only.

What statement is used to populate a table variable?

The INSERT statement following the declaration demonstrates one way to populate a declared table variable.


1 Answers

you cannot do like that,however you can use temp table to do so.newly created #temp or parmanent table will have same table structure.

Declare @t table(startdate date,enddate date,duration int)
select * into #t1 from @t 

select * from @t1
drop table #t1
like image 163
KumarHarsh Avatar answered Sep 24 '22 05:09

KumarHarsh