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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Two questions regarding Tables

Author  Topic 

Rock_query
Yak Posting Veteran

55 Posts

Posted - 2013-03-26 : 16:47:39
1. I am using SQL Express 2012. I downloaded the AdventureWorks2012 database. In the Object Explorer, I am in the AdventureWorks2012 database. Within the database, I have the 'tables' folder open showing all the tables. I am recreating the Person.CountryRegion table with 'III' appended to the end of the name. See below.

CREATE TABLE Person.CountryRegionIII
(CountryRC nvarchar(3) NOT NULL,
NameI nvarchar(50) NOT NULL,
ModifiedD datetime NOT NULL
)

The operation ran successfully, but I can't find the table in the tables folder. Where is this table and how do I refer to it?

2. Is it possible to clone a table? By that I mean create a copy of that table w/o having to manually create a new table, defining it, then copying data into that new table.

chadmat
The Chadinator

1974 Posts

Posted - 2013-03-26 : 17:14:50
Refresh the folder

-Chad
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2013-03-26 : 17:45:39
An answer to question 2, but use it at your own risk

SELECT TOP 0*
INTO CloneTable
FROM ParentTable

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-26 : 17:47:25
You can "clone" a table a couple of different ways:

1. Right click on the table in SSMS object explorer, and select Script Table as -> Create To -> New Query Editor Window. Modify the script to change whatever you need (including constraint names etc.) and then run the script. That will create the new table.

2. Run a query such as this:[code]SELECT TOP (0) * INTO YourNewTableName FROM YourOldTableName. That will create a copy of the new table. You can omit the TOP (0) part if you want to insert the rows into the table as well.

There are differences between the two approaches - select into won't copy the keys but will keep the identity property etc. Investigate and use whichever suits your needs.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-03-27 : 17:31:47
#2 - There in no direct way to clone a table as you have described. But, there are pseudo ways that might work. You can select from the source table into a new one. That, as James said, won't include the keys, indexes, computed columns, etc.. For example:
SELECT *
INTO CloneTable
FROM Source

Of course you can script out the table, but then it won't have the data in it until you migrate the data.
Go to Top of Page
   

- Advertisement -