c# - 从 sql 存储过程加载和调用 C#(程序集)

标签 c# c++ sql-server-2008 dll

假设我有简单的 C# 代码 来打印 HELLO WORLD,如图所示 in here

using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;

public class HelloWorldProc
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void HelloWorld()
    {
        SqlContext.Pipe.Send("HELLO WORLD!\n");
    }
}

所以他们在那个页面上说:

This topic provides an overview of the namespaces and libraries required to compile database objects using the Microsoft SQL Server integration with the Microsoft .NET Framework common language runtime (CLR). The topic also shows you how to write, compile, and run a simple CLR stored procedure written in Microsoft Visual C#.

CLR integration functionality is exposed in an assembly called system.data.dll, which is part of the .NET Framework. This assembly can be found in the Global Assembly Cache (GAC) as well as in the .NET Framework directory. A reference to this assembly is typically added automatically by both command line tools and Microsoft Visual Studio, so there is no need to add it manually.

创建后,(编译它并添加到路径 dll 中)您可以将该代码用作存储过程,例如:

CREATE ASSEMBLY helloworld from 'c:\helloworld.dll' WITH PERMISSION_SET = SAFE

创建程序集后,我们现在可以使用 create procedure 语句访问我们的 HelloWorld 方法。我们将调用我们的存储过程“hello”:

CREATE PROCEDURE hello
AS
EXTERNAL NAME helloworld.HelloWorldProc.HelloWorld

创建过程后,它就可以像使用 Transact-SQL 编写的普通存储过程一样运行。执行以下命令:

EXEC hello

要删除该过程:

drop procedure hello

删除过程后,您可以删除包含示例代码的程序集。

drop assembly helloworld

在此介绍之后:

我需要使用也使用外部 dll 的 C++ 代码,我的问题如下,

我怎么能像示例中那样在 C# 中使用我的 C++ 代码(也使用 extern dll),因此,在我执行存储过程时创建程序集后,以下是透明的:

  1. SQL 创建程序集,然后调用 dll 中的 C# 代码。
  2. C# 代码调用 C++ 代码(在 dll 内)
  3. C++代码调用extern dll。

所以我只做

执行你好

所有发生的事情(SQL SERVER -> C# -> C++ -> extern dll)。

  • 如何让所有这些 dll 派对继续并共存,所以我只在 SQL Server 中执行一个存储过程,比如 执行你好

我在想

[DllImport("cCode.dll")]

但是如果 C++ 代码依赖于外部 dll...我迷路了

最佳答案

好吧,如果你打算沿着这条路走下去,你可能会跳过使用 C# 作为你的 C++ dll 的包装器(因为听起来你只是想使用 SQL Server CLR 集成作为一种手段来调用 C++ 例程)。

相反,您可以在服务器上创建并注册一个 C++ COM+ 应用程序 (example),然后使用 sp_OACreate 从 SQL Server 调用它及相关procedures .仅供引用:如果需要,您也可以在 C# 中创建 COM+ 应用程序,但与 C++ dll 交互可能需要更多工作。

我认为您会更幸运地采用这种方法,因为可以将 COM+ 应用程序配置为在专用服务器进程中运行,而不是在 SQL Server 进程中运行。

也许您的情况另有规定,但正如其他人评论的那样,最好将这种“集成”留在数据库之外,并将其放入单独的应用程序层。

关于c# - 从 sql 存储过程加载和调用 C#(程序集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272931/

相关文章:

c# - 如何以及何时翻译和评估 LINQ 查询?

c# - 控制台输出的自定义格式

c++ - 声明 Reduction over Vector,在 1 个线程上运行会给出与没有 openmp 时不同的结果

c# - SQL 2008 : returning data rows as JSON?

sql - 在 SQL Server 2008 中输出嵌套的 XML

c# - Nhibernate 抛出类型为 'System.Linq.EnumerableQuery` 的对象 1[实体 ]' cannot be converted to type ' System.Linq.IQueryable`1[System.Object[]]'

c# - 是否可以创建变体值类型?

c++ - 信号处理程序中的回溯

c++ - 错误 C2065 : 'socklen_t' : undeclared identifier

sql - 如何从特定的大约中获取顶行。使用 sql server 2008 的百分比?