我们有一个后台系统,通过 MSDTC 将发票信息插入到 SQL 数据库中。存储过程,应用程序插入标题,然后是详细信息。
我已经设置了CLR插入记录时触发的标题表上的触发器。
我遇到的问题是触发器在 COMMIT TRANSACTION
之前触发这意味着可能不会填充详细信息,这是触发的流程所必需的。此外,如果系统触发 ROLLBACK TRANSACTION
触发器已经触发。
我知道触发器不能分配给 COMMIT
,但想知道是否有人有任何其他想法。
我偶然发现了一个建议的 oracle 解决方案,您可以在其中创建一个更新的物化 View ON COMMIT
,并试图找到相当于索引 View 的 TSQL,但没有实现它。
总结:
是否可以触发 COMMIT TRANSACTION
可能使用索引 View ?
CLR触发代码
向队列发送 JMS 消息,由 Sonic ESB 处理.
[Microsoft.SqlServer.Server.SqlTrigger(Name = "InvoiceTrigger", Target = "Table", Event = "FOR INSERT")]
public static void InvoiceTrigger()
{
//Declare Connection vairables
string connectionURL, connectionDomain, connectionUser, connectionPassword, connectionQueue;
//Constant
connectionUser = "user";
connectionPassword = "pass";
connectionQueue = "Queue";
//Local Environment
connectionURL = "tcp://IP:2506";
connectionDomain = "Domain1";
//Create connection sonic domain
SonicSend send = new SonicSend(connectionURL, connectionDomain, connectionUser, connectionPassword, connectionQueue);
//Send Test message to pipe
SqlCommand command;
SqlTriggerContext triggContext = SqlContext.TriggerContext;
SqlPipe pipe = SqlContext.Pipe;
SqlDataReader reader;
switch (triggContext.TriggerAction)
{
case TriggerAction.Insert:
// Retrieve the connection that the trigger is using
using (SqlConnection connection = new SqlConnection(@"context connection=true"))
{
connection.Open();
command = new SqlCommand(@"SELECT LSH_LINKCODE, DOC_CODE, LSH_DOCNUM FROM INSERTED;", connection);
reader = command.ExecuteReader();
if (reader.HasRows)
{
string xml;
char cr = (char)13;
int i = 0;
while (reader.Read())
{
xml = @"<Invoice action='insert'>";
xml += "<LinkCode>" + reader.GetString(0).ToString() + "</LinkCode>";
xml += "<DocumentCode>" + reader.GetString(1).ToString() + "</DocumentCode>";
xml += "<DocumentNumber>" + reader.GetString(2).ToString() + "</DocumentNumber>";
xml += @"</Invoice>";
i++;
send.testJMSsend(xml);
}
}
reader.Close();
}
break;
}
}
最佳答案
在有用的评论指出不可能在触发器中使用提交之后。
我查看了由触发器启动的 ESB 进程,该进程现在使用传递的信息查询数据,这解决了我的问题,因为 BEGIN TRANSACTION
对数据创建锁,直到出现 COMMIT TRANSACTION
查询才会返回结果,因此意味着在查询返回数据之前该过程不会继续,因此将始终填充发票详细信息。
如果有 ROLLBACK TRANSACTION
,该过程将按预期超时抛出错误。
关于sql - TSQL:提交时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13860816/