views:

95

answers:

4

Hi guys,

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?

+5  A: 

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

marc_s
A: 

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

Rob
A: 

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

Sylvia
A: 

Ok, I understand. I'll will decide which approach to use. Thanks for all the answers ;).

hancock