使用 "clr enabled" 部署 SQL Server Express LocalDB 数据库应用程序

deploy SQL Server Express LocalDB database app with "clr enabled"

交叉发布于 MSDN

我的应用在 codeplex

上使用 group_concat 自定义函数

在目标机器上启动应用程序时出现以下错误。

Execution of user code in the .NET framework is disabled. Enable clr enabled configuration option.

假设 localdb 安装在目标机器上,我该怎么做才能在安装的同时启用 clr?在我的机器上,我刚刚打开 SSMS 并在那里执行了脚本。

sp_configure 'clr enabled', 1; GO RECONFIGURE; GO

但是,SSMS 不会安装在大多数客户端上,我不确定如何安装以便数据库可以使用这些功能。有什么建议吗?

编辑: 我曾尝试以两种不同的方式从应用程序中用 c# 设置它,但都失败了。

 public void EnableCLR(string ConnectionString)
    {
        using(SqlConnection con = new SqlConnection(ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("sp_configure 'clr enabled', 1", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                con.Open();

                cmd.ExecuteNonQuery(); //Error: Unable to find stored procedure "sp_configure 'clr enabled', 1"
            }
        }
    }

然后我试了这个

 public void EnableCLR(string ConnectionString)
    {
        using(SqlConnection con = new SqlConnection(ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("sp_configure", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                con.Open();

                SqlParameter clrParam = new SqlParameter();

                clrParam.ParameterName = "clr enabled";

                clrParam.Value = 1;

                cmd.Parameters.Add(clrParam);

                cmd.ExecuteNonQuery(); //Error: @clr enabled is not a parameter for procedure sp_configure.
            }
        }
    }

你是如何安装 LocalDB 的?我假设您是通过连接字符串附加 MDF 文件,因此无法在 SQL 脚本中执行这些语句。

假设也没有 SQLCMD.EXE 到 运行 查询,您应该能够创建一个单独的控制台应用程序,安装程序可以在安装 LocalDB 后 运行。该控制台应用程序可以通过 SqlCommand.ExecuteNonQuery() 运行 SQL 语句。这些 SQL 语句可以是硬编码的(更难更改),也可以从 app.exe.Config 文件中获取配置 SQL。

大致如下:

SqlConnection _Connection = new SqlConnection(@"(localdb)\InstanceName");
SqlCommand _Command = null;

try
{
  _Command = _Connection.CreateCommand();
  _Connection.Open();

  _Command.CommandText = "EXEC sp_configure 'clr enabled', 1;";
  _Command.ExecuteNonQuery();

  _Command.CommandText = "RECONFIGURE;";
  _Command.ExecuteNonQuery();
}
finally
{
  if (_Command != null)
  {
    _Command.Dispose();
  }
  _Connection.Dispose();
}