Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate database creation scripts

Is it possible to generate the database creation scripts for a SQL server database from .NET?

I am using C# and I would like to create some sort of an installer project for my application on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.

like image 445
sTodorov Avatar asked Apr 26 '13 05:04

sTodorov


People also ask

How do I create a full database script in SQL Server?

Open up SQL Server Management Studio (SSMS) and connect to your database. Then right-click on your database and select Tasks -> Generate Scripts... 2. Click 'Next' on the Generate and Publish Scripts Wizard Introduction screen.

How do you generate create table script for all tables in SQL Server database?

Now right-click the database then Tasks->Generate scripts. After that a window will open. Select the database and always check "script all objects in the selected database". It will generate a script for all the tables, sp, views, functions and anything in that database.

What are database scripts?

The Database Scripts project is a series of command line scripts which will dump, erase, restore and merge databases.

What is generate script in SQL Server?

SQL Server Management Studio provides two mechanisms for generating Transact-SQL scripts. You can create scripts for multiple objects by using the Generate and Publish Scripts Wizard. You can also generate a script for individual objects or multiple objects by using the Script as menu in Object Explorer.


1 Answers

Yes, it is possible. It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:

    private StringCollection GetTransferScript(Database database)
    {
        var transfer = new Transfer(database);

        transfer.CopyAllObjects = true;
        transfer.CopyAllSynonyms = true;
        transfer.CopyData = false;

        // additional options
        transfer.Options.WithDependencies = true;
        transfer.Options.DriAll = true;
        transfer.Options.Triggers = true;
        transfer.Options.Indexes = true;
        transfer.Options.SchemaQualifyForeignKeysReferences = true;
        transfer.Options.ExtendedProperties = true;
        transfer.Options.IncludeDatabaseRoleMemberships = true;
        transfer.Options.Permissions = true;
        transfer.PreserveDbo = true;

        // generates script
        return transfer.ScriptTransfer();
    }
like image 182
Dennis Avatar answered Sep 30 '22 11:09

Dennis