我有一个非常庞大的SP,我有一个交易。我正在SP中运行算法,如果算法不成功,则回滚事务。
即使事务被回滚,我也需要记录一些数据,但是当事务回滚时,它也会回滚日志。这是正常行为,但我需要从回滚中排除该日志插入语句,以便仍然记录事务。
我有一个名为#MissingAllocationLines
的临时表,我将日志插入该表。然后,如果它回滚,我需要将#MissingAllocationLines
中的所有行插入真实表DLWMS_ALLOCATIONMISSINGLOG
这可能吗?我的示例代码在
下面create table #MissingAllocationLines
(ALLOCATIONJOBID BIGINT,
ORDERID BIGINT,
ORDERDETAILID BIGINT,
ITEMID BIGINT,
STOCKQUANTITY BIGINT,
ORDERQUANTITY BIGINT)
BEGIN TRANSACTION
WHILE(.....)
BEGIN
INSERT INTO #MissingAllocationLines (ALLOCATIONJOBID,ORDERID,ORDERDETAILID,ITEMID,STOCKQUANTITY,ORDERQUANTITY)
VALUES (@ALLOCATIONJOBID,@OrderID,@OrderDetailID,@ItemID,ISNULL(@StockFreeQuantity, 0),ISNULL(@RemainingQuantity,0))
...
...
...
END
IF(@DONE=1)
BEGIN
COMMIT TRANSACTION
END
ELSE
BEGIN
ROLLBACK TRANSCATION
INSERT INTO DLWMS_ALLOCATIONMISSINGLOG (ALLOCATIONJOBID,ORDERID,ORDERDETAILID,ITEMID,STOCKQUANTITY,ORDERQUANTITY)
SELECT ALLOCATIONJOBID,ORDERID,ORDERDETAILID,ITEMID,STOCKQUANTITY,ORDERQUANTITY
FROM #MissingAllocationLines
END
答案 0 :(得分:3)
尝试使用表变量而不是临时表。表变量不参与事务。
http://www.sqlservercentral.com/blogs/steve_jones/2010/09/21/table-variables-and-transactions/
答案 1 :(得分:1)
在catch块中,在回滚事务之前,请执行以下操作...
DECLARE @TABLE AS TABLE
(COL1 INT,
COL2 INT
...
)
INSERT INTO @TABLE
SELECT * FROM #TEMP TABLE
ROLLBACK TRANSCATION
INSERT INTO DLWMS_ALLOCATIONMISSINGLOG
select * from @table
<强>参考文献:强>
http://sqlmag.com/t-sql/table-variable-tip
答案 2 :(得分:0)
查看SAVE TRANSACTION命令。
答案 3 :(得分:0)
您可以将'remote proc transaction promotion'用作false并使用该链接服务器进行日志记录到本地服务器:代码如下
begin tran outertran
insert into t values (1)
begin tran innertran
insert into localserver.tempdb.#log values (1)
commit tran innertran
IF (@Done)
begin
commit tran outertran
end
else begin
rollback tran outertran
end
select * from #log
EXEC sp_addlinkedserver @server = N'localserver',@srvproduct = N'',@provider = N'SQLNCLI', @datasrc = @@SERVERNAME
EXEC sp_serveroption localserver,N'remote proc transaction promotion','FALSE'
EXEC sp_serveroption localserver,N'RPC OUT','TRUE' -- Enable RPC to the given server