SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
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
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

AskSQLTeam
Ask SQLTeam Question

USA
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).

Thanks
San"

Page47
Flowing Fount of Yak Knowledge

USA
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
{0}
Go to Top of Page

M.E.
Aged Yak Warrior

Canada
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

select
case when st.name = 'varchar' then sc.name + ' ' + st.name + '(' + convert(varchar(5),sc.length)+'),'
else sc.name + ' ' + st.name + ','
end
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

ValterBorges
Flowing Fount of Yak Knowledge

USA
1429 Posts

Posted - 12/12/2002 :  10:42:27  Show Profile  Reply with Quote
SELECT *
INTO #MyTempTable
FROM MyRealTable
WHERE 1=0

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



Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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.05 seconds. Powered By: Snitz Forums 2000