Introduction
In SQL Server 2005 and later versions, database objects like functions, stored procedures, etc. can be created which are already created in the CLR. In some cases, the CLR is faster than T-SQL. CLR is mainly used to do those things which are not possible with T-SQL.
How to create CRL Function?
The steps to create a CLR function are as below.
Step 1
Create Code in C# or VB.NET
In the following example, the Create function returns the total customer count present in the database.
Step 2
Generate a DLL for the preceding code and put it in a shared folder or put it on the SQL Server machine.
Step 3
We need to enable CLR in our SQL. With the help of the following command, we can enable it. Also, we can enable it from the GUI.
Step 4
Now we must register our CLR code DLL to SQL Server.
Step 5
Create a User-Defined Function, as in.
The following is another example of accepting a customer id and returning his/her name.
Note. Before dropping an assembly you must drop all references i.e. you must drop all CLR functions, SP, etc. which are created with a reference of the assembly being dropped.
Conclusion
A CLR function is useful where writing highly procedural code or using system facilities not accessible from T-SQL would be of benefit. The CLR integration layer does offer access to .Net libraries, which may be useful to get access to capabilities that T-SQL cannot support.