Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Como posso automatizar a tarefa de geração de scripts no SQL Server Management Studio 2008?


SqlPubwiz tem opções muito limitadas em comparação com a geração de script no SSMS. Por outro lado, as opções disponíveis com o SMO correspondem quase exatamente às do SSMS, sugerindo que provavelmente é o mesmo código. (Espero que a MS não o tenha escrito duas vezes!) Existem vários exemplos no MSDN como este que mostram tabelas de script como objetos individuais. No entanto, se você quiser que tudo seja script corretamente com um esquema 'completo' que inclua objetos 'DRI' (Integridade Referencial Declarativa) como chaves estrangeiras, as tabelas de script individualmente não funcionam com as dependências corretamente. Descobri que é necessário coletar todos os URNs e entregá-los ao scripter como uma matriz. Este código, modificado a partir do exemplo, funciona para mim (embora eu ouse dizer que você poderia arrumá-lo e comentar um pouco mais):
    using Microsoft.SqlServer.Management.Smo;
    using Microsoft.SqlServer.Management.Sdk.Sfc;
    // etc...

    // Connect to the local, default instance of SQL Server. 
    Server srv = new Server();

    // Reference the database.  
    Database db = srv.Databases["YOURDBHERE"];

    Scripter scrp = new Scripter(srv);
    scrp.Options.ScriptDrops = false;
    scrp.Options.WithDependencies = true;
    scrp.Options.Indexes = true;   // To include indexes
    scrp.Options.DriAllConstraints = true;   // to include referential constraints in the script
    scrp.Options.Triggers = true;
    scrp.Options.FullTextIndexes = true;
    scrp.Options.NoCollation = false;
    scrp.Options.Bindings = true;
    scrp.Options.IncludeIfNotExists = false;
    scrp.Options.ScriptBatchTerminator = true;
    scrp.Options.ExtendedProperties = true;

    scrp.PrefetchObjects = true; // some sources suggest this may speed things up

    var urns = new List<Urn>();

    // Iterate through the tables in database and script each one   
    foreach (Table tb in db.Tables)
    {
        // check if the table is not a system table
        if (tb.IsSystemObject == false)
        {
            urns.Add(tb.Urn);
        }
    }

    // Iterate through the views in database and script each one. Display the script.   
    foreach (View view in db.Views)
    {
        // check if the view is not a system object
        if (view.IsSystemObject == false)
        {
            urns.Add(view.Urn);
        }
    }

    // Iterate through the stored procedures in database and script each one. Display the script.   
    foreach (StoredProcedure sp in db.StoredProcedures)
    {
        // check if the procedure is not a system object
        if (sp.IsSystemObject == false)
        {
            urns.Add(sp.Urn);
        }
    }

    StringBuilder builder = new StringBuilder();
    System.Collections.Specialized.StringCollection sc = scrp.Script(urns.ToArray());
    foreach (string st in sc)
    {
        // It seems each string is a sensible batch, and putting GO after it makes it work in tools like SSMS.
        // Wrapping each string in an 'exec' statement would work better if using SqlCommand to run the script.
        builder.AppendLine(st);
        builder.AppendLine("GO");
    }

    return builder.ToString();