0

I have a requirement where I need to create multiple tables with the help of some existing tables but the new tables would have some different names.

For example:

Existing Table Names:

INT_Employees,
INT_HumanResource,
INT_Payroll,
INT_Contacts etc..

New Tables should have prefix STG so it should look like:

STG_Employees,
STG_HumanResource,
STG_Payroll,
STG_Contacts etc..

Note: There are around 127 tables and we need to create new 127 tables with prefix STG_.

Thanks in Advance.

2
  • Do you need to copy the data, or just the structure of the table? Commented Feb 2, 2017 at 17:46
  • Hi Austin,Just the structure Commented Feb 2, 2017 at 17:48

1 Answer 1

1

If you are just trying to copy the table structure you can use select into with a where predicate that will prevent any rows from being returned.

select * into STG_Employees from INT_Employees where 1 = 0

Just repeat this for each table.

--EDIT--

Here is an example of you can leverage dynamic sql to do this task instead of resorting to loops. We simply use sys.tables to help us generate our sql statement.

declare @sql nvarchar(max) = ''

select @sql = @sql + 'select * into ' + stuff(name, 1, 4, 'STG_') + ' from ' + name + ' where 1 = 0;'
from sys.tables 
where name like 'INT[_]%'

select @sql --once your comfortable the sql being generated is correct simply uncomment the next line
--exec sp_executesql @sql

Please note that if you want primary keys, indexes, foreign keys, computed columns etc you will need to generate those scripts another way. This will only generate the table structures.

Sign up to request clarification or add additional context in comments.

8 Comments

Is there a way we can use a looping concept for all these tables ?
Why use looping? Do you have a list of all the tables?
Yeah, we can get it from sys.tables by using the Object_ID
Be aware this method won't create any constraints, keys, indexes, identity property, or computed column definitions present in the source tables. Another option would be to script all the tables & run a find-replace on the script.
@GarethLyons it will pick up identity but you are spot on that the rest of these potentially very important pieces will be skipped.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.