2017-07-31 61 views
0

如何通過使用存儲過程插入數據後顯示的ID,我的樣本存儲過程是這樣的..顯示ID

CREATE PROCEDURE [dbo].[insertResidence] 
@Fname varchar(50), 
@Lname varchar(50), 
@Mname varchar(50), 
@Bdate varchar(50), 
@BirthPlace varchar(50), 
@CivStat varchar(50), 
@Purok varchar(50), 
@Religion varchar(50), 
@Gender varchar(50), 
@CitShip varchar(50) 

AS 
    Begin tran one; 
    Declare @resId INT; 
    INSERT INTO [tbl_Residence] (resFname, resLname, resMname, resBdate, resBirthPlace, resGender) VALUES (@Fname,@Lname,@Mname,@Bdate,@BirthPlace,@Gender); 
    Select @resId = SCOPE_IDENTITY(); 
    NSERT INTO [tbl_Religion] (resId, religion) VALUES (@resId,@Religion); 
    INSERT INTO [tbl_Purok] (resId,pur_sit) VALUES (@resId,@Purok); 
    INSERT INTO [tbl_Citizenship] (resId,citship) VALUES (@resID,@Purok); 
    Select resId from tbl_Residence WHERE resId = @resId; 
    commit tran; 
RETURN 

插入數據後,我想顯示標籤或textboxt中的id。

我在交易中使用ExecuteNonQuery() .. 這是交易插入數據

public int insertRes(Informations info) 
    { 

     //Insert Residence Informations 
     SqlCommand cmd = new SqlCommand("InsertResidence"); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@FName", SqlDbType.VarChar).Value = info.Fname; 
     cmd.Parameters.AddWithValue("@LName", SqlDbType.VarChar).Value = info.Lname; 
     cmd.Parameters.AddWithValue("@MName", SqlDbType.VarChar).Value = info.Mname; 
     cmd.Parameters.AddWithValue("@BDate", SqlDbType.VarChar).Value = info.Bdate; 
     cmd.Parameters.AddWithValue("@BirthPlace", SqlDbType.VarChar).Value = info.BirthPlace; 
     cmd.Parameters.AddWithValue("@CivStat", SqlDbType.VarChar).Value = info.CivStat; 
     cmd.Parameters.AddWithValue("@Purok", SqlDbType.VarChar).Value = info.purok; 
     cmd.Parameters.AddWithValue("@Religion", SqlDbType.VarChar).Value = info.Religion; 
     cmd.Parameters.AddWithValue("@Gender", SqlDbType.VarChar).Value = info.Gender; 
     cmd.Parameters.AddWithValue("@CitShip", SqlDbType.VarChar).Value = info.CitShip; 
     return db.ExeNonQuery(cmd); 
    } 

UI層的代碼:

UI layer

業務層:

Business logic layer

+1

[查看最近的ID(https://stackoverflow.com/questions/5228780/how-to-get-last -inserted-id) – CodingYoshi

回答

1

ExecuteNonQuery只會返回您的命令影響的行數。 使用ExecuteScalar,它將返回resId。

要進行顯示:

int resId = (int)cmd.ExecuteScalar(); 

然後在您的UI:

lblMyLabel.Text = resId.ToString(); 
+0

但我如何使用我的交易在標籤中顯示它 – Cooper

+0

已更新答案以給出代碼片段 – BlackSpy

+0

我需要在我的參數中添加此代碼嗎? cmd.Parameters.AddWithValue(「@ resId」,SqlDbType.VarChar).Value = info.Id; – Cooper