我试图在不使用存储过程的情况下编写嵌套事务。它的结构是什么。我尝试了但是得到了一些错误。我的一些变量没有发现,当我试图声明它们时,它说它们已经被声明了。
Begin Transaction campOffer
Begin Transaction loyaltyCard
Begin Transaction marketingList
Insert Into marketing_list values (@custID, @name, @dOB,
@gender, @parish, @mobile, @mProvider, @mStatus)
Select @@TRANCOUNT
Commit Transaction
End
Insert Into Loyalty_Card (Member_ID) Values (@memID)
Select @@TRANCOUNT
Commit Transaction
End
Insert Into Campaign_Offer values (@offID, @offDate, @custID, @offValue, @prodName, @accepStatus, @empID)
Select @@TRANCOUNT
Commit Transaction
End
答案 0 :(得分:1)
嵌套交易是一个神话。好。你可以拥有它们。但SQL Server仅将最外层事务视为真实事务。你不能回滚内在的。它将回滚最外层的事务。有关详细信息,请参阅COMMIT和ROLLBACK语句的MSDN常规备注部分。
您对BEGIN TRANSACTION
有一个小问题。这不是像BEGIN
这样的块语句。因此,一旦声明了变量,它的范围就不会留在COMMIT或ROLLBACK语句中。
Begin Transaction campOffer --@@TRANCOUNT = 1
Begin Transaction loyaltyCard --@@TRANCOUNT = 2
Begin Transaction marketingList --@@TRANCOUNT = 3
Insert Into marketing_list values (@custID, @name, @dOB, @gender,
@parish, @mobile, @mProvider, @mStatus)
Select @@TRANCOUNT
Commit Transaction --@@TRANCOUNT = 2
--END -- does not correspond to any BEGIN statement
Insert Into Loyalty_Card (Member_ID) Values (@memID)
Select @@TRANCOUNT
Commit Transaction --@@TRANCOUNT = 1
-- END -- does not correspond to any BEGIN statement
Insert Into Campaign_Offer values (@offID, @offDate, @custID, @offValue, @prodName, @accepStatus, @empID)
Select @@TRANCOUNT
Commit Transaction --@@TRANCOUNT = 0... outer transaction is now committed.
--END -- does not correspond to any BEGIN statement
答案 1 :(得分:0)
- 在存储过程之外,您必须声明然后为所有参数设置值。
declare @custID as int, @name as varchar(10), @dOB as date,@gender as varchar(1)
--.... (do this for all with appropriate data types)
-- then set the desired values.
Set @custID = 101;
Set @name = 'johnny';
--(Set all param values)
Begin Transaction campOffer
Begin Transaction loyaltyCard
Begin Transaction marketingList
Insert Into marketing_list values (@custID, @name, @dOB,
@gender, @parish, @mobile, @mProvider, @mStatus)
Select @@TRANCOUNT
Commit Transaction
End
Insert Into Loyalty_Card (Member_ID) Values (@memID)
Select @@TRANCOUNT
Commit Transaction
End
Insert Into Campaign_Offer values (@offID, @offDate, @custID, @offValue, @prodName, @accepStatus, @empID)
Select @@TRANCOUNT
Commit Transaction
End