Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7960021
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:39:44+00:00 2026-06-04T04:39:44+00:00

I have several functions in an assembly dll named UserFunctions.dll , for example :

  • 0

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 ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:39:45+00:00Added an answer on June 4, 2026 at 4:39 am

    I have tested and debugged it :

    static void Main(string[] args)
    {
      Assembly clrAssembly = Assembly.LoadFrom(@"Path\to\your\assembly.dll");
      string sql = CreateFunctionsFromAssembly(clrAssembly, permissionSetType.UNSAFE);
      File.WriteAllText(sqlFile, sql);
    }
    
    
    /// <summary>
    /// permissions available for an assembly dll in sql server
    /// </summary>
    public enum permissionSetType { SAFE, EXTERNAL_ACCESS, UNSAFE };
    
    
    /// <summary>
    /// generate sql from an assembly dll with all functions with attribute SqlFunction
    /// </summary>
    /// <param name="clrAssembly">assembly object</param>
    /// <param name="permissionSet">sql server permission set</param>
    /// <returns>sql script</returns>
    public static string CreateFunctionsFromAssembly(Assembly clrAssembly, permissionSetType permissionSet)
    {
        const string sqlTemplate = @"
          -- Delete all functions from assembly '{0}'
          DECLARE @sql NVARCHAR(MAX)
          SET @sql = 'DROP FUNCTION ' + STUFF(
            (
                SELECT
                    ', ' + assembly_method 
                FROM
                    sys.assembly_modules
                WHERE
                    assembly_id IN (SELECT assembly_id FROM sys.assemblies WHERE name = '{0}')
                FOR XML PATH('')
            ), 1, 1, '')
          IF @sql IS NOT NULL EXEC sp_executesql @sql
          GO
    
          -- Delete existing assembly '{0}' if necessary
          IF EXISTS(SELECT 1 FROM sys.assemblies WHERE name = '{0}')
            DROP ASSEMBLY {0};
          GO
    
          {1}
          GO
    
          -- Create all functions from assembly '{0}'
        ";
        string assemblyName = clrAssembly.GetName().Name;
    
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(sqlTemplate, assemblyName, CreateSqlFromAssemblyDll(clrAssembly, permissionSet));
    
        foreach (Type classInfo in clrAssembly.GetTypes())
        {
            foreach (MethodInfo methodInfo in classInfo.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                if (Attribute.IsDefined(methodInfo, typeof(SqlFunctionAttribute)))
                {
                    StringBuilder methodParameters = new StringBuilder();
                    bool firstParameter = true;
                    foreach (ParameterInfo paramInfo in methodInfo.GetParameters())
                    {
                        if (firstParameter)
                             firstParameter = false;
                        else
                            methodParameters.Append(", ");
                        methodParameters.AppendFormat(@"@{0} {1}", paramInfo.Name, ConvertClrTypeToSql(paramInfo.ParameterType));
                    }
                    string returnType = ConvertClrTypeToSql(methodInfo.ReturnParameter.ParameterType);
                    string methodName = methodInfo.Name;
                    string className = (classInfo.Namespace == null ? "" : classInfo.Namespace + ".") + classInfo.Name;
                    string externalName = string.Format(@"{0}.[{1}].{2}", assemblyName, className, methodName);
                    sql.AppendFormat(@"CREATE FUNCTION {0}({1}) RETURNS {2} AS EXTERNAL NAME {3};"
                                    , methodName, methodParameters, returnType, externalName)
                       .Append("\nGO\n");
                }
            }
        }
        return sql.ToString();
    }
    
    
    /// <summary>
    /// Generate sql script to create assembly
    /// </summary>
    /// <param name="clrAssembly"></param>
    /// <param name="permissionSet">sql server permission set</param>
    /// <returns></returns>
    public static string CreateSqlFromAssemblyDll(Assembly clrAssembly, permissionSetType permissionSet)
    {
        const string sqlTemplate = @"
          -- Create assembly '{0}' from dll
          CREATE ASSEMBLY [{0}] 
            AUTHORIZATION [dbo]
            FROM 0x{2}
            WITH PERMISSION_SET = {1};
        ";
    
        StringBuilder bytes = new StringBuilder();
        using (FileStream dll = File.OpenRead(clrAssembly.Location))
        {
            int @byte;
            while ((@byte = dll.ReadByte()) >= 0)
                bytes.AppendFormat("{0:X2}", @byte);
        }
        string sql = String.Format(sqlTemplate, clrAssembly.GetName().Name, permissionSet, bytes);
    
        return sql;
    }
    
    
    /// <summary>
    /// Convert clr type to sql type
    /// </summary>
    /// <param name="clrType">clr type</param>
    /// <returns>sql type</returns>
    private static string ConvertClrTypeToSql(Type clrType)
    {
        switch (clrType.Name)
        {
            case "SqlString":
                return "NVARCHAR(MAX)";
            case "SqlDateTime":
                return "DATETIME";
            case "SqlInt16":
                return "SMALLINT";
            case "SqlInt32":
                return "INTEGER";
            case "SqlInt64":
                return "BIGINT";
            case "SqlBoolean":
                return "BIT";
            case "SqlMoney":
                return "MONEY";
            case "SqlSingle":
                return "REAL";
            case "SqlDouble":
                return "DOUBLE";
            case "SqlDecimal":
                return "DECIMAL(18,0)";
            case "SqlBinary":
                return "VARBINARY(MAX)";
            default:
                throw new ArgumentOutOfRangeException(clrType.Name + " is not a valid sql type.");
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that holds several vectors of objects: struct ComponentA { public:
Currently I have several functions, named function1.m , function2.m , function3.m , ..., function10.m
I have a Bourne Shell script that has several functions in it, and allows
I have a certain loop occurring several times in various functions in my code.
I have noticed that Google Toolbox for Mac replaces several SQLite built-in functions (LOWER/UPPER,
My application has several independent top-level windows, which all have completely different functions/workflows. I
I have several javascript functions to validate the input data in textbox, so it
I have several custom functions that I use frequently in R. Rather than souce
following setup, i have several generic functions, and i need to choose the type
I have several functions that are used to bind events with divs on the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.