Question

I have a SQL Server Project in my Solution (VS 2012/.Net 4.5). The only reason for that project is that I needed to create a CLR function that I can call from some of my stored procedures. It works great and life is awesome. However, I have to Manually Publish the SQL project in order to get that function into my database.

Is there a way, ideally while I am Seeding the database (which is an Entity Framework 5.0 Code-First database) to do some sort of execute command or publish of my CLR function Programmatically so I do not have this extra manual step?

TIA

Was it helpful?

Solution

Yes, you just need to pass the correct SQL. Here is a snippet of a SQL script of mine that adds Regex support as a stored procedure, you can modify this to your needs.

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RegexMatch]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
    DROP FUNCTION [dbo].[RegexMatch]
GO
IF  EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N'Msdn.SqlRegex')
    DROP ASSEMBLY [Msdn.SqlRegex]
GO
--------------------------------
--Create the clr program to do the regex
--------------------------------
CREATE ASSEMBLY [Msdn.SqlRegex]
AUTHORIZATION [dbo]
FROM 0x4D5A90000300000004000000F(SNIP)
WITH PERMISSION_SET = SAFE

GO

ALTER ASSEMBLY [Msdn.SqlRegex]
ADD FILE FROM 0xEFBBBF7573696E672053797374656D(SNIP)
AS N'Properties\AssemblyInfo.cs'

GO

ALTER ASSEMBLY [Msdn.SqlRegex]
ADD FILE FROM 0x7573696E672053797374(SNIP)
AS N'RegexMatch.cs'
GO

CREATE FUNCTION [dbo].[RegexMatch](@input [nvarchar](max), @pattern [nvarchar](4000))
RETURNS [bit] WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [Msdn.SqlRegex].[UserDefinedFunctions].[RegexMatch]
GO

To get the three byte arrays just add the assembly once by hand and then go in to Sql Server Management studio and go to Programability->Assemblies right click on your assembly and go to Script Assembly as->Create To->New Query Editor Window and use that as your source.

OTHER TIPS

Assemblies can be created, dropped and altered with T-SQL:

CREATE ASSEMBLY
ALTER ASSEMBLY
DROP ASSEMBLY

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top