在存储过程中使用事务

时间:2014-08-08 06:22:43

标签: sql-server-2008 stored-procedures

我创建了一个存储过程,我想在此使用事务。那么如何在这个存储过程中使用事务呢?哪个部分将启动事务,因为INSERTUPDATE都在此存储过程中。

这是我的存储过程:

ALTER PROCEDURE [dbo].[usp_InsertUpdateADAlertRecipient]
    @AD_User_ID int,
    @AD_Client_ID int,
    @AD_Org_ID int,
    @IsActive bit,
    @Created datetime,
    @Createdby int,
    @Updated datetime,
    @Updatedby int,
    @AD_Alertrecipient_ID int,
    @AD_AlertRule_ID int,
    @AD_Role_ID int,
    @Sendemail bit
AS

SET NOCOUNT ON

IF EXISTS(SELECT [AD_Alertrecipient_ID] FROM [dbo].[AD_AlertRecipient] WHERE [AD_Alertrecipient_ID] = @AD_Alertrecipient_ID)
BEGIN 


UPDATE [dbo].[AD_AlertRecipient] SET
    [AD_User_ID] = @AD_User_ID,
    [AD_Client_ID] = @AD_Client_ID,
    [AD_Org_ID] = @AD_Org_ID,
    [IsActive] = @IsActive,
    [Created] = @Created,
    [Createdby] = @Createdby,
    [Updated] = @Updated,
    [Updatedby] = @Updatedby,
    [AD_AlertRule_ID] = @AD_AlertRule_ID,
    [AD_Role_ID] = @AD_Role_ID,
    [Sendemail] = @Sendemail
WHERE
    [AD_Alertrecipient_ID] = @AD_Alertrecipient_ID
    select @AD_Alertrecipient_ID
END 

ELSE
BEGIN
    INSERT INTO [dbo].[AD_AlertRecipient] (
        [AD_User_ID],
        [AD_Client_ID],
        [AD_Org_ID],
        [IsActive],
        [Created],
        [Createdby],
        [Updated],
        [Updatedby],
        --[AD_Alertrecipient_ID],
        [AD_AlertRule_ID],
        [AD_Role_ID],
        [Sendemail]
    ) VALUES (
        @AD_User_ID,
        @AD_Client_ID,
        @AD_Org_ID,
        @IsActive,
        @Created,
        @Createdby,
        @Updated,
        @Updatedby,
        --@AD_Alertrecipient_ID,
        @AD_AlertRule_ID,
        @AD_Role_ID,
        @Sendemail
    )
    SELECT SCOPE_IDENTITY()
END

感谢并等待您的回复。

0 个答案:

没有答案