Generate database creation scripts

前端 未结 3 1143
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-09 06:43

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

3条回答
  •  日久生厌
    2021-02-09 06:57

    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();
        }
    

提交回复
热议问题