简体   繁体   中英

Call dll function from sql stored procedure using the current connection

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' )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM