我有一个用 C# 4.0 编写并部署在 SQL Server 2014 上的 SQL CLR 触发器。每当在 SQL Server 的表中发生插入时,此 CLR 触发器的工作就是将该行导入 Oracle 数据库中。所以基本上我必须在 SQL Server 2014 中的表上触发插入查询时将数据导入 Oracle 数据库。这是我的第一个 CLR SQL 触发器项目,下面是我正在做的事情:
[SecurityCritical]
[OraclePermission(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
[SqlTrigger(Name = "FetchSurvey", Target = "temp", Event = "FOR INSERT")]
public static void FetchSurvey()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
// Create result set to store data
DataSet resultSet = new DataSet();
// Create a new SQL command
using (SqlCommand command = new SqlCommand("SELECT * FROM INSERTED"))
{
// Create a new SQL connection
using (command.Connection = new SqlConnection("context connection=true"))
{
// Connect to the database
command.Connection.Open();
// Execute procedure
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(resultSet);
}
// Disconnect from the database
command.Connection.Close();
}
}
SqlPipe sqlP = SqlContext.Pipe;
// Return data
if (resultSet.Tables.Count > 0)
SaveSurvey(resultSet);
sqlP.Send("Finaly its done!!");
}
public static void SaveSurvey(DataSet dsSurvey)
{
using (OracleConnection con = new OracleConnection("my oracle connection string"))
{
if (con.State == ConnectionState.Closed)
con.Open();
DataRowView drv = dsSurvey.Tables[0].DefaultView[0];
using (OracleCommand cmd = new OracleCommand("AddMetaData", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("V_id", drv["TemplateID"]);
cmd.Parameters.AddWithValue("V_Title", drv["TemplateName"]);
cmd.Parameters.AddWithValue("V_CreatedBy", drv["CreatedBy"]);
cmd.Parameters.AddWithValue("V_IsActive", drv["IsActive"]);
cmd.ExecuteNonQuery();
}
}
}
这是我创建组装/部署触发器的代码:
CREATE ASSEMBLY TriggerImportSurvey
FROM 'C:\ImportSurvey\SQL-CLR-Trigger.dll'
With Permission_Set = External_Access;
现在的问题是,每当我在 SQL Server 中运行插入查询以插入数据时,都会在 SQL Server 中出现以下错误:
消息 6522,级别 16,状态 1,过程
tri_InsertSurvey_clr
,第 18
行在执行用户定义的例程或聚合“tri_InsertSurvey_clr”期间发生 .NET Framework 错误:System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods System.InvalidOperationException: at Triggers.FetchSurvey()
tri_InsertSurvey_clr
是每当我运行插入语句时负责执行程序集的触发器。
请告诉我我缺少什么以便我收到此错误,此外,如果有更优雅的方式来实现 CLR SQL 触发器,那么也请提出建议。
注意:当我尝试使用 SQL Server 中的触发器保存数据时,我成功了,但是现在当我尝试将其保存在 Oracle 数据库中时,我收到了这个错误。Oracle 数据库也安装在另一台机器上。