I have several functions in an assembly dll named UserFunctions.dll, for example :
public static partial class VariousFunctions
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlBoolean RegexMatch(SqlString expression, SqlString pattern)
{
...
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlInt32 WorkingDays(SqlDateTime startDateTime, SqlDateTime endDateTime)
{
...
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString getVersion()
{
...
}
...
}
And I want to generate the sql script with a c# function, to create or update automatically all functions with attribute SqlFunction contained in this dll.
This sql script should look like this :
-- Delete all functions from assembly 'UserFunctions'
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'DROP FUNCTION ' + STUFF(
(
SELECT
', ' + QUOTENAME(assembly_method)
FROM
sys.assembly_modules
WHERE
assembly_id IN (SELECT assembly_id FROM sys.assemblies WHERE name = 'UserFunctions')
FOR XML PATH('')
), 1, 1, '')
-- SELECT @sql
IF @sql IS NOT NULL EXEC sp_executesql @sql
-- Create all functions from assembly 'UserFunctions'
CREATE FUNCTION RegexMatch(@expression NVARCHAR(MAX), @pattern NVARCHAR(MAX)) RETURNS BIT
AS EXTERNAL NAME UserFunctions.VariousFunctions.RegexMatch;
GO
CREATE FUNCTION WorkingDays(@startDateTime DATETIME, @endDateTime DATETIME) RETURNS INTEGER
AS EXTERNAL NAME UserFunctions.VariousFunctions.WorkingDays;
GO
CREATE FUNCTION getVersion() RETURNS VARCHAR(MAX)
AS EXTERNAL NAME UserFunctions.VariousFunctions.getVersion;
GO
The first part is very simple, but for the second part this is probably possible using the reflection methods of the classes Type, MethodInfo and ParameterInfo.
Someone has already done this ?
I have tested and debugged it :