Generating sql code programmatically

前端 未结 5 1927
清酒与你
清酒与你 2020-12-03 02:28

i have generated scripts manually through Generate script in tasks menu by right clicking database.

Now my problem

5条回答
  •  温柔的废话
    2020-12-03 02:35

    As it's already mentioned, you cas use SMO to do this, here is a an example using C# to script a database, I mentioned few options, but as it is in the post of @David Brabant, you can specify the values of many options.

    public string ScriptDatabase()
    {
          var sb = new StringBuilder();
    
          var server = new Server(@"ServerName");
          var databse = server.Databases["DatabaseName"];
    
          var scripter = new Scripter(server);
          scripter.Options.ScriptDrops = false;
          scripter.Options.WithDependencies = true;
          scripter.Options.IncludeHeaders = true;
          //And so on ....
    
    
          var smoObjects = new Urn[1];
          foreach (Table t in databse.Tables)
          {
              smoObjects[0] = t.Urn;
              if (t.IsSystemObject == false)
              {
                  StringCollection sc = scripter.Script(smoObjects);
    
                  foreach (var st in sc)
                  {
                      sb.Append(st);
                  }
               }
           }
                return sb.ToString();
     }
    

    This link may help you getting and scripting stored procedures

提交回复
热议问题