HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

3rd party dll in SQL Server CLR

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
dll3rdsqlpartyclrserver

Problem

I need to use a third party DLL in a trigger c# code in SQL Server CLR

But when I try to add reference it just shows some DLLs from SQL Server.

How can I add my third party dll to SQL Server?

Solution

You can only add references to those assemblies which have been registered with Sql Server. If they are not registered, they will no show up in the Add References dialog.

There are a number of steps you'll need to do register a DLL, firstly you'll need to reconfigure your database:

ALTER DATABASE [MyDatabase] SET TRUSTWORTHY ON;
sp_configure 'clr enabled', 1;
RECONFIGURE;


Once this is done, Sql Server is CLR enabled. Next, you'll need to register your assembly:

CREATE ASSEMBLY [MyAssembly] AUTHORIZATION [MyUser]
FROM 'C:\CLR\MyAssembly.dll'
WITH PERMISSION_SET = SAFE


If this last script runs correctly, the assembly is now registered, and will appear in the Add References dialog.

What you will need to consider though, is the application security of your Sql Server CLR configuration:

  • Prefer to register an assembly as SAFE, only in exceptional circumstances should you use EXTERNAL_ACCESS or UNSAFE.



  • Don't expect to be able to do everything you can on Full-trust CLR (i.e., not the CLR hosted by Sql Server) - the SQLCLR is a sandboxed runtime.



  • Don't try and load assemblies dynamically, as Assembly.Load() is purposefully restricted.



  • You may need to ensure the 3rd party library is signed with a public key if you plan on using UNSAFE.



  • Code executing runs in the context of the identity of the service running Sql Server (I think!)



  • Database access made from a hosted assembly (e.g. via context connection = true;) runs in the context of the connected user, so you need to make sure you are aware what access that library has to your data.

Code Snippets

ALTER DATABASE [MyDatabase] SET TRUSTWORTHY ON;
sp_configure 'clr enabled', 1;
RECONFIGURE;
CREATE ASSEMBLY [MyAssembly] AUTHORIZATION [MyUser]
FROM 'C:\CLR\MyAssembly.dll'
WITH PERMISSION_SET = SAFE

Context

StackExchange Database Administrators Q#12479, answer score: 15

Revisions (0)

No revisions yet.