12

有没有办法使用 C# 从 SQL Server 2005 Express 数据库中获取存储过程?我想以与您可以使用 SQL Server Management Studio 编写脚本相同的方式导出所有这些数据,而无需安装 GUI。

我已经看到了一些通过 PowerShell 进行操作的参考,但最终我真正想要的是 C# 控制台应用程序。

澄清....

我想编写存储过程的脚本。通过 的列表Select * from sys.procedures很有帮助,但最后我需要编写每个脚本。

4

12 回答 12

22

您可以为此使用 SMO。首先,将这些程序集的引用添加到您的项目中:

  • Microsoft.SqlServer.ConnectionInfo
  • 微软.SqlServer.Smo
  • Microsoft.SqlServer.SmoEnum

它们位于 GAC 中(浏览到 C:\WINDOWS\assembly 文件夹)。

使用以下代码作为脚本存储过程的示例:

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<SqlSmoObject> list = new List<SqlSmoObject>();
      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());
   }
}

另请参阅:SQL Server:SMO 脚本基础

于 2008-10-04T00:56:38.820 回答
6

只需从 SYS.PROCEDURES 读取 SELECT NAME 的输出,然后为每个存储过程调用 EXEC sp_HelpText SPNAME,您将获得每行一行文本的记录集。

于 2008-10-03T23:46:59.930 回答
3
;WITH ROUTINES AS (
    -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit
    SELECT o.type_desc AS ROUTINE_TYPE
            ,o.[name] AS ROUTINE_NAME
            ,m.definition AS ROUTINE_DEFINITION
    FROM sys.sql_modules AS m
    INNER JOIN sys.objects AS o
        ON m.object_id = o.object_id
)
SELECT *
FROM ROUTINES
于 2008-10-06T15:01:50.440 回答
2

此博客文章建议对您的数据库运行此操作:

select * from sys.procedures
于 2008-10-03T23:42:32.357 回答
2

您可以使用:

DataTable  dtProcs = sqlConn.GetSchema("Procedures", new string[] { databaseName });
DataTable  dtProcParams = sqlConn.GetSchema("ProcedureParameters", new string[] { databaseName });

如果需要,您还可以获得各种其他模式信息,如表、索引等。

您可以在此处获取有关 GetSchema()的信息,并在此处获取有关 SQL Server 架构集合的信息

编辑:对不起,这对实际编写信息没有帮助,但我想这是有用的信息。

于 2008-10-08T15:31:15.637 回答
2
public static void GenerateTableScript()
    {
        Server databaseServer = default(Server);//DataBase Server Name
        databaseServer = new Server("yourDatabase Server Name");
        string strFileName = @"C:\Images\Your FileName_" + DateTime.Today.ToString("yyyyMMdd") + ".sql"; //20120720`enter code here
        if (System.IO.File.Exists(strFileName))
            System.IO.File.Delete(strFileName);
        List<SqlSmoObject> list = new List<SqlSmoObject>();
        Scripter scripter = new Scripter(databaseServer);
        Database dbUltimateSurvey = databaseServer.Databases["YourDataBaseName"];//DataBase Name
        //Table scripting Writing
        DataTable dataTable1 = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table);
        foreach (DataRow drTable in dataTable1.Rows)
        {
            //string strTableSchema = (string)drTable["Schema"];
            //if (strTableSchema == "dbo")
            //    continue;
            Table dbTable = (Table)databaseServer.GetSmoObject(new Urn((string)drTable["Urn"]));
            if (!dbTable.IsSystemObject)
                if (dbTable.Name.Contains("SASTool_"))
                    list.Add(dbTable);
        }
        scripter.Server = databaseServer;
        scripter.Options.IncludeHeaders = true;
        scripter.Options.SchemaQualify = true;
        scripter.Options.ToFileOnly = true;
        scripter.Options.FileName = strFileName;
        scripter.Options.DriAll = true;
        scripter.Options.AppendToFile = true;
        scripter.Script(list.ToArray());//Table Script completed
        //Store Procedures scripting Writing
        list = new List<SqlSmoObject>();
        DataTable dataTable = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcedure);
        foreach (DataRow row in dataTable.Rows)
        {
            string sSchema = (string)row["Schema"];
            if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
                continue;
            StoredProcedure sp = (StoredProcedure)databaseServer.GetSmoObject(
               new Urn((string)row["Urn"]));
            if (!sp.IsSystemObject)
                if (sp.Name.Contains("custom_"))
                    list.Add(sp);
        }
        scripter.Server = databaseServer;
        scripter.Options.IncludeHeaders = true;
        scripter.Options.SchemaQualify = true;
        scripter.Options.ToFileOnly = true;
        scripter.Options.FileName = strFileName;
        scripter.Options.DriAll = true;
        scripter.Options.AppendToFile = true;
        scripter.Script(list.ToArray());   // Stored procedure Script completed
    }
于 2012-07-26T16:11:25.497 回答
0

您可以编写 C# 代码在数据库上运行以下查询。

Select * from sys.procedures
于 2008-10-03T23:43:49.890 回答
0

我认为这是您真正想要的:

select SPECIFIC_NAME,ROUTINE_DEFINITION from information_schema.routines

那里还有很多其他有用的列......

于 2008-10-04T00:18:14.983 回答
0
begin
--select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Products' 
--Declare the Table variable 
DECLARE @GeneratedStoredProcedures TABLE
(
        Number INT IDENTITY(1,1), --Auto incrementing Identity column
        name VARCHAR(300) --The string value
)

--Decalre a variable to remember the position of the current delimiter
DECLARE @CurrentDelimiterPositionVar INT 
declare @sqlCode varchar(max)
--Decalre a variable to remember the number of rows in the table
DECLARE @Count INT

--Populate the TABLE variable using some logic
INSERT INTO @GeneratedStoredProcedures SELECT name FROM sys.procedures where name like 'procGen_%'

--Initialize the looper variable
SET @CurrentDelimiterPositionVar = 1

--Determine the number of rows in the Table
SELECT @Count=max(Number) from @GeneratedStoredProcedures

--A variable to hold the currently selected value from the table
DECLARE @CurrentValue varchar(300);

--Loop through until all row processing is done
WHILE @CurrentDelimiterPositionVar <= @Count
BEGIN
    --Load current value from the Table
    SELECT @CurrentValue = name FROM @GeneratedStoredProcedures WHERE Number = @CurrentDelimiterPositionVar 
    --Process the current value
    --print @CurrentValue
    set @sqlCode = 'drop procedure ' + @CurrentValue
    print @sqlCode
    --exec (@sqlCode)


    --Increment loop counter
    SET @CurrentDelimiterPositionVar = @CurrentDelimiterPositionVar + 1;
END

end
于 2009-06-18T10:25:40.767 回答
0

如果您在 sqlmetal.exe(从数据库生成代码的 LINQ-to-SQL 的独立部分)上打开一罐反射器,您可以看到它用于获取所有存储过程和函数列表的 SQL 语句. SQL 与此答案中的 SQL 相似,但并不完全相同。

于 2009-11-05T16:52:39.747 回答
0

这是我刚刚在MSSQL中测试和使用过的SQL

SELECT NAME from SYS.PROCEDURES 
order by name

如果您需要查找特定名称或子字符串/文本

SELECT NAME from SYS.PROCEDURES 
where name like '%<TEXT_TO_LOOK_FOR>%'
order by name

替换为例如:

SELECT NAME from SYS.PROCEDURES 
where name like '%CUSTOMER%'
order by name

并打电话

EXEC sp_HelpText SPNAME 

对于每个存储过程,您将获得每行一行文本的记录集

于 2015-12-14T16:52:58.430 回答
-1

假设您有SqlConnection名为sqlCon的对象,最简单的方法是调用 sqlCon.GetSchema("Procedures")

于 2015-03-02T12:48:39.033 回答