将UDF与SQL查询一起使用时出错

时间:2014-03-20 09:30:00

标签: c# sql sql-server sqlclr

我使用C#as ::

将SQL项目模板用于Visual Studio,从而制作了一个CLR
  [Microsoft.SqlServer.Server.SqlFunction()]
    public static SqlDateTime ScalarUDF(SqlInt64 CompanyID)
    {
        SqlInt64 temp = CompanyID;
        string zoneId = "Singapore Standard Time";
        TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
        DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);

        return new SqlDateTime(result);
    }

还使用query ::

将UDF创建为SQL
-- Install Assembly
CREATE ASSEMBLY UDF_Trial FROM 'C:\Users\Rahul\Documents\visual studio 2013\Projects\UDF_Trial\UDF_Trial\bin\Debug\UDF_Trial.dll'
GO
-- Create ScalarUDF
CREATE FUNCTION [dbo].[ScalarUDF](@CompanyID bigint)
RETURNS datetime
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME UDF_Trial.UserDefinedFunctions.ScalarUDF;
GO

但是在执行UDF时我遇到了一些错误:

我正在执行UDF,

select [dbo].[ScalarUDF](15)

但是将例外情况视为::

Msg 6522, Level 16, State 2, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "ScalarUDF": 
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.

The protected resources (only available with full trust) were: All
The demanded resources were: MayLeakOnAbort

System.Security.HostProtectionException: 
   at UserDefinedFunctions.ScalarUDF(SqlInt64 CompanyID)
.

我还在创建Assembly :: {

时将权限设为UNSAFE

CREATE ASSEMBLY UDF_Trial FROM' C:\ Users \ Rahul \ Desktop \ pro_temp \ UDF_Trial.dll' WITH PERMISSION_SET = UNSAFE; GO

但是在这种情况下我得错误为::

CREATE ASSEMBLY for assembly 'UDF_Trial' failed because assembly 'UDF_Trial' is not authorized for PERMISSION_SET = UNSAFE.  The assembly is authorized when either of the following is true: the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.

1 个答案:

答案 0 :(得分:3)

我将数据库的可信度设置为ON为::

ALTER DATABASE Learn SET TRUSTWORTHY ON

并将Assembly创建为::

CREATE ASSEMBLY UDF_Blog FROM 'C:\Users\Rahul\Documents\visual studio 2013\Projects\UDF_Trial\UDF_Trial\bin\Debug\UDF_Trial.dll'
WITH PERMISSION_SET = UNSAFE;
GO

问题解决了。