简体   繁体   中英

Clone entire database with a SP

I'm trying to find out if this is possible, but so far I haven't found out any good solutions. What I would like to achieve is write a stored procedure that can clone a database but without the stored data. That means all tables, views, constraints, keys and indexes should be included but without any data. Can it be done?

Sure - your stored proc would have to read the system catalog views to find out what objects are in the database, determine their potential dependencies, and then create a single or a collection of SQL scripts which re-create the database, and execute those.

It's possible - not very nice and easy to do. Especially the dependencies between objects might cause more headaches than first meets the eye....

You could also:

  • use something like SQL Server Management Studio (if you're on SQL Server - you didn't specify) and create the scripts manually, and just re-execute them on a separate server

  • use a "diff" tool like Redgate SQL Compare to compare two servers and have the second one brought up to date

In SQL Server you can roll through the system tables (sys.tables, sys.columns, etc.) and construct things one at a time. It's going to be very manual and error prone at the beginning, but it should become systematic pretty quickly.

Another way to do it is to write something in .Net using SMO. Check out this link:

http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated

I've successfully used the Microsoft SQL Server Database Publishing Wizard for this purpose. It's pretty straightforward, no coding needed. Here's a sample call:

sqlpubwiz script -d DatabaseName -S ServerName -schemaonly C:\\Projects2\\Junk\\ DatabaseName.sql

I believe the default is to create both data and schema, but you can use the schemaonly parameter.

Download it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM