【问题标题】:Create sql server functions from an assembly dll automatically自动从程序集 dll 创建 sql server 函数
【发布时间】:2012-05-23 21:03:02
【问题描述】:

我在一个名为 UserFunctions.dll 的程序集 dll 中有几个函数,例如:

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()
    {
      ...
    }

    ...
}

我想用一个 c# 函数生成 sql 脚本,以自动创建或更新此 dll 中包含的属性 SqlFunction 的所有函数。 此 sql 脚本应如下所示:

-- 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

第一部分非常简单,但对于第二部分,这可能使用 Type、MethodInfo 和 ParameterInfo 类的反射方法来实现。 有人已经这样做了吗?

【问题讨论】:

    标签: c# sql-server sql-server-2008 tsql sql-server-2005


    【解决方案1】:

    我已经测试并调试过了:

    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.");
        }
    }
    

    【讨论】:

      【解决方案2】:

      我建议您执行以下操作: 从 Visual Studio,转到文件 > 新项目...然后从模板中选择 SQL SERVER

      从你的项目中获取属性

      提到在项目设置中,你可以确定你的“目标平台” 在 SQLCLR 中,您可以选择您的编程语言

      向您的项目添加一个新项目(SQL CLR C# 用户定义函数)

      编写你的函数

      编写代码后,右键单击您的项目并首先构建您的项目,然后将其发布到您的 sql server

      在下一个窗口中,设置与 sql 服务器和数据库的连接

      完成后,您可以看到已经创建了正确的程序集和函数 在你的数据库中

      【讨论】:

        【解决方案3】:

        一种方法可能是在已知函数中使用反射,该函数编译在 dll(如果它是你的)或 CLR dll 中,你可以创建和引用。在那里,您可以使用 .NET 的完整 REGEX 支持将创建函数所需的匹配名称返回给 SQL SERVER。

        这是一种解决方法,但我不知道使用 .NET 反射的原生 TSQL 方法

        -编辑-

        如果你需要从 .NET 创建一个 TSQL 脚本,你可以使用类似的东西(未调试,但大多数东西应该在那里)

        public string encode(Type containerClass, string SSRVassemblyName)
            {
                string proTSQLcommand="";
                MethodInfo[] methodName = containerClass.GetMethods();
                foreach (MethodInfo method in methodName)
                {
                    proTSQLcommand += "CREATE FUNCTION ";
                    if (method.ReflectedType.IsPublic)
                    {
                        bool hasParams = false;
                        proTSQLcommand += method.Name +"(";
                        ParameterInfo[] curmethodParams = method.GetParameters();
                        if (curmethodParams.Length > 0)
                            for (int i = 0; i < curmethodParams.Length; i++)
                            {
                                proTSQLcommand +=(hasParams?",":"")+ String.Format("@{0} {1}",curmethodParams[i].Name,CLRtypeTranscoder(curmethodParams[i].ParameterType.Name)) ;
                                hasParams = true;
                            }
                        proTSQLcommand += (hasParams ? "," : "") + String.Format("@RetVal {0} OUT", CLRtypeTranscoder(method.ReturnType.Name));
        
                    }
                    //note that I have moved the result of the function to an output parameter 
                    proTSQLcommand += "RETURNS INT ";
                    //watch this! the assembly name you have to use is the one of SSRV, to reference the one of the CLR library you have to use square brackets as follows
                    proTSQLcommand += String.Format("AS EXTERNAL NAME {0}.[{1}.{2}].{3}; GO ",SSRVassemblyName, GetAssemblyName(containerClass.Name),containerClass.Name,method.Name);
                }
                return proTSQLcommand;
            }
            public string CLRtypeTranscoder(string CLRtype)
            { //required as the mapping of CLR type depends on the edition of SQL SERVER you are using
                switch (CLRtype.ToUpper())
                {
                    case "STRING":
                        return "VARCHAR(MAX)";
                    case "INT":
                        return "INT";
                }
                throw new   ArgumentOutOfRangeException();
            }
            public static String GetAssemblyName(String typeName)
            {
                foreach (Assembly currentassemblAssy in AppDomain.CurrentDomain.GetAssemblies())
                {
                    Type t = currentassemblAssy.GetType(typeName, false, true);
                    if (t != null) { return currentassemblAssy.FullName; }
                }
        
                return "not found";
            }
        

        【讨论】:

        • 也许我没有很好地解释问题,但我想使用c#函数而不是TSQL方法生成之前描述的sql。
        猜你喜欢
        • 2020-06-11
        • 1970-01-01
        • 2014-05-07
        • 2018-11-10
        • 2015-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-07
        相关资源
        最近更新 更多