CLR is Common Language Runtime, and Stored Procedures are routine stored procedures of the database. Thus, CLR Stored Procedures are a combination of both.
In CLR, stored procedures are implemented as public static methods on a class in a Microsoft.NET Framework assembly.
Here is a simple CLR stored procedure which will print the text message.
[Microsoft.SqlServer.Server.SqlProcedure]
public static void PrintText()
{
SqlPipe sqlP = SqlContext.Pipe;
sqlP.Send("This is a first stored procedure using CLR database object");
}
The CREATE PROCEDURE
statement will create the stored procedure using the SqlCLRDemo assembly.
CREATE PROCEDURE PrintText
AS EXTERNAL NAME SqlClrDemo.StoredProcedures.PrintText
You can also pass parameters to CLR stored procedure. The following method takes two parameters, the string data passed in the first parameter with additional string data will be returned as an output.
[Microsoft.SqlServer.Server.SqlProcedure]
public static void PrintTextByPassingParams(string strInParam, out string strOutParam)
{
strOutParam = $"Hi '{strInParam}', this is a stored procedure with parameters using CLR database object.";
}
The following CREATE PROCEDURE
statement will create the PrintTextByPassingParams
stored procedure which takes two parameters.
CREATE PROCEDURE dbo.PrintTextByPassingParams
(
@strInParam NVARCHAR (MAX) NULL,
@strOutParam NVARCHAR (MAX) NULL OUTPUT
)
AS EXTERNAL NAME SqlClrDemo.StoredProcedures.PrintTextByPassingParams
You can also use the Publish option to create the stored procedure automatically. The following example will execute PrintTextByPassingParams
.
DECLARE @message nvarchar(max)
EXEC dbo.PrintTextByPassingParams @strInParam = 'Andy', @strOutParam = @message OUTPUT;
SELECT @message;
The expected output of the above example is as follows.
Hi 'Andy', this is a stored procedure with parameters using CLR database object.