【发布时间】:2014-03-21 06:36:20
【问题描述】:
我觉得这可能和This Issue一样
我也参考了它,但仍然无法解决我的问题。 这是我第一次创建任何 CLR 并遇到问题。
我已经在 C# 中开发了一个 CLR::
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime GetTimeForCompanyID(SqlInt64 CompanyID)
{
string strZoneID;
string connStr = @"data source=.;initial catalog=dbName;Integrated Security=SSPI;user id=RJ;password=RJ@123;enlist=false;";
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand select = new SqlCommand(
"select SettingValue from CompanySetting where CompanyID="+CompanyID+" and Setting='TimeZone'",
connection))
{
using (SqlDataReader reader = select.ExecuteReader())
{
strZoneID = reader.GetString(0);
}
}
}
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(strZoneID);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
SqlDateTime Final = result;
return Final;
}
}
并且将Assembly创建为SQL如下::
1) 我首先在主数据库中创建了Assembly Key::
use master
CREATE ASYMMETRIC KEY MyDllKey FROM EXECUTABLE FILE = 'C:\Temp\CueBusinessFunctions.dll'
CREATE LOGIN MyDllLogin FROM ASYMMETRIC KEY MyDllKey
GRANT EXTERNAL ACCESS ASSEMBLY TO MyDllLogin
2) 将程序集创建为::
use Learn
CREATE ASSEMBLY CueBusinessFunctions FROM 'C:\Projects\CueBusinessFunctions.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
3) 创建 CLR UDF 为::
CREATE FUNCTION [dbo].[GetTimeForCompanyID](@CompanyID bigint)
RETURNS datetime
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME CueBusinessFunctions.UserDefinedFunctions.GetTimeForCompanyID;
GO
但问题是在执行 UDF 时为::
select [dbo].[GetTimeForCompanyID](1)
我得到的错误是::
Msg 6522, Level 16, State 1, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "GetTimeForCompanyID":
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.GetTimeForCompanyID(SqlInt64 CompanyID)
.
【问题讨论】:
-
你试过什么?如果您避免外部 sql 调用,它会起作用吗?没有时区处理怎么样?如果您的方法被硬编码为返回 null,它仍然会失败吗?
标签: c# sql sql-server clr sqlclr