将 UDF 与 SQL Query 一起使用时出错
Posted
技术标签:
【中文标题】将 UDF 与 SQL Query 一起使用时出错【英文标题】:Getting error when using UDF with SQL Query 【发布时间】:2014-03-20 09:29:59 【问题描述】:我已经通过在 Visual Studio 中使用 SQL 项目模板制作了一个 CLR,使用语言 C# as::
[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
的权限::
从“C:\Users\Rahul\Desktop\pro_temp\UDF_Trial.dll”创建组件 UDF_Trial WITH PERMISSION_SET = 不安全; 去吧
但在这种情况下,我收到错误为::
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.
【问题讨论】:
可能重复***.com/questions/6568751/… @MoslemBenDhaou 给出正确的答案,而不是查看其他人的答案。 提问前请阅读 *** 指南。 ***.com/help/duplicates 【参考方案1】:我已将数据库的可信度设置为 ON::
ALTER DATABASE Learn SET TRUSTWORTHY ON
并将程序集创建为 ::
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
问题就解决了。
【讨论】:
以上是关于将 UDF 与 SQL Query 一起使用时出错的主要内容,如果未能解决你的问题,请参考以下文章
Spark - Hive UDF 与 Spark-SQL 一起使用,但不与 DataFrame 一起使用