Simple way to programmatically get all stored procedures

后端 未结 12 2146
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 09:22

Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it o

12条回答
  •  庸人自扰
    2020-12-24 09:35

    You can use SMO for that. First of all, add references to these assemblies to your project:

    • Microsoft.SqlServer.ConnectionInfo
    • Microsoft.SqlServer.Smo
    • Microsoft.SqlServer.SmoEnum

    They are located in the GAC (browse to C:\WINDOWS\assembly folder).

    Use the following code as an example of scripting stored procedures:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using Microsoft.SqlServer.Management.Smo;
    
    class Program
    {
       static void Main(string[] args)
       {
          Server server = new Server(@".\SQLEXPRESS");
          Database db = server.Databases["Northwind"];
          List list = new List();
          DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure);
          foreach (DataRow row in dataTable.Rows)
          {
             string sSchema = (string)row["Schema"];
             if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
                continue;
             StoredProcedure sp = (StoredProcedure)server.GetSmoObject(
                new Urn((string)row["Urn"]));
             if (!sp.IsSystemObject)
                list.Add(sp);
          }
          Scripter scripter = new Scripter();
          scripter.Server = server;
          scripter.Options.IncludeHeaders = true;
          scripter.Options.SchemaQualify = true;
          scripter.Options.ToFileOnly = true;
          scripter.Options.FileName = @"C:\StoredProcedures.sql";
          scripter.Script(list.ToArray());
       }
    }
    

    See also: SQL Server: SMO Scripting Basics.

提交回复
热议问题