Call dll function from sql stored procedure using the current connection

早过忘川 提交于 2019-12-03 23:09:59

问题


Can I call a dll from a stored procedure using the open connection?

I have a dll that gets data from SQL Server and I don't want to open a new connection when I call it from the stored procedure.

Thank you

Here is an exemple

public class Class1
{
    public static SqlString GetName(SqlString str)
    {
        SqlCommand cmd = new SqlCommand(str.ToString());
        cmd.CommandType = System.Data.CommandType.Text;

        string name = cmd.ExecuteScalar().ToString();
        return name;
    }
}

and this is the SQL code

CREATE FUNCTION fn_TestConnection
(
    @str nvarchar(255)
)
RETURNS nvarchar(max)
AS EXTERNAL NAME TestConnection.[TestConnection.Class1].GetName
GO

SELECT dbo.fn_TestConnection('SELECT FName FROM Clients WHERE Id = 1' )

回答1:


These instructions are for Microsoft SQL Server Management Studio 2014.

Import the Assembly

First of all you need to import that assembly into your database inside SQL Server Management Studio by navigating to the New Assembly dialog window:

DatabaseName -> Programmability -> Assemblies -> (Right Click) 'New Assembly...'

Inside the 'New Assembly' dialog window, chose Browse under the Path to assembly field and select the assembly you want to import. Adjust Permissions and click ok.

Wrap Assembly Methods in a SQL Function

Next you need to create sql function to wrap your assembly method like this:

CREATE FUNCTION [dbo].[fn_funcName](@str [varchar](max))
RETURNS 
   varchar(max) 
WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [YourSqlAssemblyName].[YourAssemblyName.Class1].[GetName]

If you want to return table from your function read about SqlFunctionAttribute in .NET.



来源:https://stackoverflow.com/questions/29916790/call-dll-function-from-sql-stored-procedure-using-the-current-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!