2013-05-27 37 views
1

我有三個表 - 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想要做這樣的事情時有錯誤,主鍵韓元不會增加。我該怎麼做?

回答

1

I just want to have the emp_id ... that is inserted by the first query of the transaction. How can i acheive this?

你可以只聲明一個局部變量來存儲的SCOPE_IDENTITY()結果。然後你可以使用在隨後的聲明這個變量:

... 
begin transaction 
declare @emp_id int 

insert into [dbo].[Employee]([start_date]) 
values(@start_date) 

-- store for later use  
set @emp_id = SCOPE_IDENTITY() 

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, @emp_id); 
--- here ----------------------------> ^^^^^^^ 

insert into [dbo].[Login](username,userpassword,security_question,security_answer,emp_id) 
values(@username,@password,@security_question,@security_answer, @emp_id); 
--- here -----------------------------------------------------> ^^^^^^^ 

... 

I want to do something like when there is error,primary key won't increase.How should i do this?

我不認爲有一個簡單的方法來做到這一點 - 你將有每個錯誤後重新播種的標識值:

DBCC CHECKIDENT (<table_name>, RESEED) 

我覺得這很容易出錯(你會打電話給上述的所有錯誤?),而不是一個好主意。另請參閱MSDN上的DBCC CHECKIDENT

+0

謝謝你chue x先生。對於第二個問題,有沒有什麼辦法可以只在交易成功時增加主鍵的值? –

+0

@shrawan_lakhe - 我不相信。正如我上面提到的,你必須在出錯後重置種子。 –