Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Declaring table variable to have the same shape of existing user table
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Ask SQLTeam Question

0 Posts

Posted - 12/12/2002 :  08:56:52  Show Profile  Visit AskSQLTeam's Homepage  Reply with Quote
San writes "Is there a way to declare a table variable to have the same shape (meaning same columns and column types) of an existing user table without explicitly specifying all the column names and column types?

Eg., Say I have a table called Person with 15 columns. I want a local table variable to have the same structure as Person. I know I can do

declare @myPersonTable (col1, col1Type.....col15 col15Type).


Flowing Fount of Yak Knowledge

2878 Posts

Posted - 12/12/2002 :  10:29:19  Show Profile  Reply with Quote
No, but you can with temp tables....

select * into #sysdb from sysdatabase


Jay White
Go to Top of Page

Aged Yak Warrior

539 Posts

Posted - 12/12/2002 :  10:40:50  Show Profile  Reply with Quote
I like using an automated script to get all that. This script will look up all the info you need from the syscolumns and systypes table

case when = 'varchar' then + ' ' + + '(' + convert(varchar(5),sc.length)+'),'
else + ' ' + + ','
from syscolumns sc inner join systypes st on st.xtype = sc.xtype where id = object_id('resource_data_seq_administration')
order by colid

the results will be

col1 varchar(40),
col2 int,

and so on. Copy paste the result (easiest if you tell query analyzer to spit out everything into a text file) and do a couple modifcations. You'll need to remove the comma from the last line (haven't quite figured out a way to automate that)

Hope it helps... typing out column names and data types can take waaaay to long sometimes

SQL isn't just a hobby, It's an addiction
Go to Top of Page

Flowing Fount of Yak Knowledge

1429 Posts

Posted - 12/12/2002 :  10:42:27  Show Profile  Reply with Quote
INTO #MyTempTable
FROM MyRealTable

This will create #MyTempTable with same structure and zero records.

Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000