如何修改以下代码来添加事务?

时间:2012-11-28 05:52:35

标签: sql-server

我是Stored过程和事务的新手。

我编写了一个将数据插入两个表的存储过程。这是SP:

Begin

SET NOCOUNT ON 

Declare @Parcel_Id int

INSERT INTO 
        Parcel([Code],[Title],
               [Is_Parcel_Equal_To_Property],
               [Property_Id],[Property_Type_Id],
               [Plot_No],[Phone],[Fax],[Email],
               [Administrator_Name],
               [Watchman_Name],
               [Remark],
               [List_in_Retail_Leasing_Module],
               [Landlord_Id],
               [Country_Id],[State_Id],[Community_Id],[MainRoad_Id],
               [Address],
               [Is_Active],
               [Added_On_Date],[Added_By]) 
        VALUES(@Code,@Title,
               @Is_Parcel_Equal_To_Property,
               @Property_Id,@Property_Type_Id,
               @Plot_No,@Phone,@Fax,@Email,
               @Administrator_Name,
               @Watchman_Name,
               @Remark,
               @List_in_Retail_Leasing_Module,
               @Landlord_Id,
               @Country_Id,@State_Id,@Community_Id,@MainRoad_Id,
               @Address,
               @Is_Active,
               @Added_On_Date,@Added_By) 

Set @Parcel_Id = SCOPE_IDENTITY()

INSERT INTO Parcel_Spacifications
        ([Parcel_Id],[Apartments],[Villas],[Retails],[Offices],[Labour_Camp],
         [Warehouses],[Total_Car_Parks],[Floors],[Year_Of_Construction],
         [Built_Up_Area],[Plot_Area],[No_Of_Basements],[Is_Special_Project])
        VALUES (@Parcel_Id,@Apartments,@Villas,@Retails,@Offices,@Labour_Camp,
                @Warehouses,@Total_Car_Parks,@Floors,@Year_Of_Construction,
                @Built_Up_Area,@Plot_Area,@No_Of_Basements,@Is_Special_Project)               
End
RETURN @Parcel_Id

现在我想使用事务,怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用BEGIN TRANCOMMIT包装代码,如下所示:

BEGIN

SET NOCOUNT ON

Declare @Parcel_ID int

BEGIN TRAN

...

COMMIT

END

RETURN @Parcel_ID

您应该阅读文档here中的备注。他们解释了交易的运作方式。