How do you use the CREATE ASSEMBLY statement to create a new assembly from a .NET DLL?
Posted by TinaGrn
Last Updated: June 15, 2024
The CREATE ASSEMBLY statement in SQL Server is used to create a new assembly from a .NET DLL. This allows SQL Server to integrate .NET code (written in languages like C# or VB.NET) into T-SQL stored procedures, functions, triggers, and more. Here’s how to use the CREATE ASSEMBLY statement: 1. Prepare the .NET DLL: Ensure that you have the .NET assembly (DLL) ready that you want to load into SQL Server. Make sure that it's compiled against a compatible version of the .NET Framework and that the appropriate methods are marked with the relevant attributes (like SqlFunction, SqlProcedure, etc., if applicable). 2. Use the CREATE ASSEMBLY statement: You can create the assembly in SQL Server by specifying the path to the DLL. Here's a basic syntax:
CREATE ASSEMBLY [AssemblyName]
   FROM 'C:\path\to\your\assembly.dll'
   WITH PERMISSION_SET = [UNSAFE | EXTERNAL_ACCESS | SAFE]
- AssemblyName: The name you want to assign to the assembly in SQL Server. - C:\path\to\your\assembly.dll: Full file path to the .NET assembly on the server. - PERMISSION_SET: Defines the permission level for the assembly. The options are: - SAFE: Assemblies that do not access external resources and run in a restricted environment. - EXTERNAL_ACCESS: Assemblies that access external resources (like file system or network). - UNSAFE: Assemblies that can do anything, including access the operating system. Requires appropriate trust settings.
Example
Here's an example SQL script to create an assembly:
CREATE ASSEMBLY MyClrAssembly
FROM 'C:\Assemblies\MyClrLibrary.dll'
WITH PERMISSION_SET = SAFE;
Important Notes
- SQL Server Version: Make sure your SQL Server version supports CLR integration, which was introduced in SQL Server 2005. - Enabling CLR: Before you can create assemblies, CLR integration must be enabled on your SQL Server instance using the following command:
sp_configure 'clr enabled', 1;
   RECONFIGURE;
- File path accessibility: The account under which SQL Server is running must have access to the path specified for the DLL. This generally means it should be on a local drive accessible by SQL Server. - Security implications: Be cautious with the UNSAFE and EXTERNAL_ACCESS permission sets, as they can pose security risks. Always follow best practices regarding security and permissions when working with CLR assemblies. - Error Handling: If there are issues when creating the assembly, SQL Server will return an error message that should give a clue about what might be wrong (e.g., path issues, permission issues, etc.). After creating the assembly, you can then create functions, procedures, or triggers that leverage the .NET code, using the appropriate CREATE FUNCTION, CREATE PROCEDURE, or CREATE TRIGGER statements.