Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all. there is two tables with a relation between. I need use transactions because of concurrency issues but i don't know how use.the code is here:

SQL
CREATE PROCEDURE [dbo].[InsertRowInPersonelInfo]
(@personelcode varchar (20),@firstname nvarchar(50),@lastname nvarchar(50),
	@employmenttype nvarchar(50),@employmentdate char(10))
as
set nocount on
begin
insert into PersonelInfo(PersonelCode,FirstName,LastName)
 Values(@personelcode,@firstname,@lastname)

DECLARE @lstprsnlID INT
set @lstprsnlID = SCOPE_IDENTITY();
                                                                                                                                                                                                                                                                                                      				   insert into EmploymentInfo(FK_pID,EmploymentType,EmploymentDate)                                                           						Values(@lstprsnlID,@employmenttype,@employmentdate)
END
set nocount off
GO
Posted
Updated 27-Jan-14 20:45pm
v2

 
Share this answer
 
Hi,

There are several ways to use transactions. You can do it like this (modified and added code in bold):
SQL
CREATE PROCEDURE [dbo].[InsertRowInPersonelInfo]
(@personelcode varchar (20),@firstname nvarchar(50),@lastname nvarchar(50),
    @employmenttype nvarchar(50),@employmentdate char(10))
AS
BEGIN
	SET NOCOUNT ON;
	SET XACT_ABORT ON;

	BEGIN TRY
	  BEGIN TRANSACTION;
		insert into PersonelInfo(PersonelCode,FirstName,LastName)
		 Values(@personelcode,@firstname,@lastname)

		DECLARE @lstprsnlID INT
		set @lstprsnlID = SCOPE_IDENTITY();

		insert into EmploymentInfo(FK_pID,EmploymentType,EmploymentDate)
		Values(@lstprsnlID,@employmenttype,@employmentdate)
		
	  COMMIT TRANSACTION;
	END TRY

	BEGIN CATCH	
	  IF (XACT_STATE()) = -1
	    ROLLBACK TRANSACTION;
	  ELSE IF (XACT_STATE()) = 1
	    COMMIT TRANSACTION;
	END CATCH;

END		
GO

You can find more information here:
1. http://technet.microsoft.com/en-us/library/ms175976.aspx[^]
(B. Using TRY…CATCH in a transaction; C. Using TRY…CATCH with XACT_STATE)
2. http://technet.microsoft.com/en-us/library/ms174377.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900