Question

Scenario: I have an existing application that uses C# to call normal SQL Server Stored Procedures. I am thinking about deleting some of the existing stored procedures and replacing them with CLR Stored Procedures. I have never written a CLR Stored Procedure.

Question:

Provided the CLR Stored Procedures have identical names and parameters as the stored procedures they are replacing. Will I have to make any changes to the C# code that calls the stored procedures?

Was it helpful?

Solution

Once you make a CLR proc, you also make a stored proc that invokes the underlying CLR proc -- thus, no change needed in the client app.

There are really pretty simply to write. Less so to debug.

Unless you open up security holes you are limited to .net Framework 2.0 code -- an easily overlooked gotcha in my experience.

Also make sure you will have the needed permissions (or a DBA willing to install them for your) before you invest much time.

ADDED Database binding code example below:

-- You must do the following once to enable CLR procs
-- sp_configure 'clr enabled', 1 
-- reconfigure

-- This adds .net 3.5 core to sql, reduces DB security, not recommended by MS
-- ALTER DATABASE [Mercedes] SET TRUSTWORTHY ON
-- Create assembly [System.Core] from 'C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\system.core.dll' with permission_set = unsafe 

-- Assuming the custom CLR dll is c:\abc\SqlModules\adlib.dll

/* If you are "rebinding" to this first

drop proc MB_ProcessInboundFiles
drop proc MB_Hello
drop assembly MB

*/

create assembly MB from 'c:\abc\SqlModules\adlib.dll'
with permission_set = EXTERNAL_ACCESS
GO

CREATE PROCEDURE MB_Hello (@say nvarchar(80)) WITH EXECUTE AS CALLER AS
EXTERNAL NAME MB.MBLib.MBhello

CREATE PROCEDURE MB_ProcessInboundFiles (@FtpInbound nvarchar(200), @FtpProcessed nvarchar(200)) WITH EXECUTE AS CALLER AS
EXTERNAL NAME MB.MBLib.MBProcessInboundFiles

-- add a quick test of the binding
exec MB_Hello 'Hi Dan'

And this is the C# guts of MB_hEllo

  [SqlProcedure]
  public static void MBhello(SqlString yousaid)
  {
    if (yousaid.IsNull)
    {
      yousaid = "Not too chatty are you " + Environment.UserDomainName + "\\" + Environment.UserName;
      SqlContext.Pipe.Send("Mercedes Benz says, '" + yousaid.ToString() + "'\n");
    }
    else
    {
      SqlContext.Pipe.Send("Mercedes Benz says, you said '" + yousaid.ToString() + "'\n");
    }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top