我有三個表 - Employee,Contact和Login。 Employee表具有emp_id作爲具有標識值的主鍵。聯繫人表具有emp_id作爲引用Employee表的emp_id的外鍵,並且登錄表也具有emp_id作爲引用Employee表的emp_id的外鍵。所有表都具有自動增加的主鍵,因爲它們都被設置爲標識(1,1)。需要在ms sql查詢中使用IDENT_CURRENT('tablename')的建議
這裏是我的sql查詢:
create procedure [dbo].[sp_registerEmp]
@start_date datetime,
@first_name varchar(50),
@middle_name varchar(50),
@last_name varchar(50),
@father_name varchar(50),
@grandfather_name varchar(50),
@country varchar(20),
@mobile_no int,
@email_id varchar(30),
@designation varchar(30),
@username varchar(20),
@password varchar(15),
@security_question varchar(150),
@security_answer varchar(50)
as
begin
begin try
begin transaction
insert into [dbo].[Employee]([start_date])
values(@start_date)
insert into [dbo].[Contact](first_name,middle_name,last_name,father_name,grandfather_name,
country,mobile_no,email_id,emp_id)
values(@first_name,@middle_name,@last_name,@father_name,@grandfather_name,
@country,@mobile_no,@email_id,SCOPE_IDENTITY());
insert into [dbo].[Login](username,userpassword,security_question,security_answer,emp_id)
values(@username,@password,@security_question,@security_answer,IDENT_CURRENT('Employee'));
commit transaction
end try
begin catch
rollback transaction
end catch
end
現在我的問題是,作爲IDENT_CURRENT(「表名」),無論返回該表中生成的最後一個標識值的會話,並使用IDENT_CURRENT scope.Now(」 tablename')可能不會給出所需的emp_id,在這些情況下,我可能有登錄表,這是爲一個用戶,但爲另一個用戶創建的。我只想爲事務的第一個查詢所插入的登錄表擁有emp_id。如何實現這一目標?
的另一個問題是,當從Visual Studio沉綿存在錯誤執行存儲過程,主鍵爲每個刀片增加嘗試的失敗無關和success.I想要做這樣的事情時有錯誤,主鍵韓元不會增加。我該怎麼做?
謝謝你chue x先生。對於第二個問題,有沒有什麼辦法可以只在交易成功時增加主鍵的值? –
@shrawan_lakhe - 我不相信。正如我上面提到的,你必須在出錯後重置種子。 –