在 C# 中读取和更改 Sql 服务器对象

Read and alter Sql Server object in c#

我编写了一个示例 Sql 存储过程。

  USE [Db]
  GO   

  SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  ALTER PROCEDURE [dbo].[usp_TestProcedure] 
  AS
  BEGIN

     SET NOCOUNT ON;
     PRINT 'Good evening'
 END

它工作正常。现在我想使用 c# 读取和更改此存储过程(以及 db 对象,如函数和视图)。可以使用 c# 完成吗?
我正在使用 Server 2014 和 C#4.5。

您可能想在 C# 中使用 DDL:Click here 如果您想在 C# 中执行此操作,则必须使用 ServerConnection 而不是标准的 SqlConnection。看这个例子:

    public bool RunScriptsInTransaction(string script)
    {
        ServerConnection sCon = new ServerConnection(this.m_dbConnection);
        sCon.BeginTransaction();
        try
        {
            sCon.ExecuteNonQuery(script);
            sCon.CommitTransaction();
        }
        catch (Exception e)
        {
            sCon.RollBackTransaction();
            return false;
        }
        return true;
    }

您必须添加引用才能使用 ServerConnction:

也许您需要安装 SQLSysClrTypes、SharedManagementObject 并在您想要 运行 的地方重新启动机器。

我现在不知道你有什么 SQL 服务器,但对于 SQL 2014 x64 它将是:

  1. 这里有 link 个要下载的 ms 文件:Get it from here 您需要从列表中检查:

ENU\x64\SQLSysClrTypes.msi

ENU\x64\SharedManagementObjects.msi

下载安装并重启。

  1. 这里有方法的完整代码(请在此过程中将 sql 连接字符串参数更改为您的服务器连接字符串):

    public static bool RunScriptsInTransaction(string script)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Server=YourSqlServer;Initial Catalog = YourDbName;User Id=YourUserName;Password=YourPassword;";
        con.Open();
    
        ServerConnection sCon = new ServerConnection(con);
        sCon.BeginTransaction();
        try
        {
            sCon.ExecuteNonQuery(script);
            sCon.CommitTransaction();
        }
        catch (Exception e)
        {
            sCon.RollBackTransaction();
            return false;
        }
        finally
        {
            con.Close();
        }
        return true;
    }
    

到运行它只是写:

        RunScriptsInTransaction(@"
    ALTER PROCEDURE [dbo].[usp_TestProcedure] 
      AS
      BEGIN

         SET NOCOUNT ON;
         PRINT 'Good evening'
     END

    GO
    ");