2012-09-13 16 views
0

代碼中的最後插入我的存儲過程插入喜歡這個獲取背後

insert into Profile_Master(FirstName,LastName,Dob,Gender,MobileNo,Country,State,EmailId,Password) 
values 
(@FirstName,@LastName,@Dob,@Gender,@MobileNo,@Country,@State,@EmailId,@Password) 
set @id=SCOPE_IDENTITY() 
return 
end 

我想在代碼中的最後插入記錄的背後,如何捕捉到的價值?

  pid = cmd1.Parameters.Add("@id", System.Data.SqlDbType.Int); 
      pid.Direction = System.Data.ParameterDirection.Output; 
      int res = Convert.ToInt32(pid.Value); 
      HttpContext.Current.Session["value"] = res.ToString(); 

這裏我得到res爲0,所以值沒有得到更新在第二頁。

+0

這裏有一個偉大的博客條目:http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record –

+0

你在調用'cm1.ExecuteNonQuery ()'在讀取'pid'值之前? –

+0

我在讀取pid值後調用cmd1.ExecuteNonQuery()。 –

回答

0

當您調用存儲過程時,您應該已經定義了所有參數,包括@ID和ParameterDirection.Output。這允許您在存儲過程退出時讀取參數的值。

像這樣的事情

using(SqlConnection conn = new SqlConnection(CONNECTION_STRING)) 
{ 
    conn.Open(); 
    SqlCommand command = conn.CreateCommand(); 
    command.CommandType = CommandType.StoredProcedure; 

    // Add all of your input parameters.... 

    SqlParameter pID = command.Parameters.Add 
       ("@ID",SqlDbType.Int); 
    pID.Direction = ParameterDirection.Output; 
    command.CommandText = "YourInsertProc"; 
    command.ExecuteNonQuery(); 

    // After executing the stored procedure, the SCOPE_IDENTITY() value 
    // could be read from the parameter value. 
    int result = Convert.ToInt32(pID.Value);  
} 

,如果你需要將結果傳遞給你可以使用會話變量

Page.Session["EMailID"] = pID.Value; 

,並在第二頁重讀它第二頁

if(Page.Session["EMailID"] != null) 
    emailID = Convert.ToInt32(Page.Session["EMailID"]); 

作爲第二種可能性,使用QueryString傳遞值

url = "secondPage.aspx?emailID=" + pID.Value.ToString(); 

int emailID = Convert.ToInt32(Page.Request["emailID"]); 
+0

更新了問題...檢查一次。 –

+0

我的情景是,我有兩個頁面只是插入值,然後它將進入下一頁基於ID我必須更新一些其他值,以便如何從存儲過程做到這一點?基於Emailid我想更新值 –

+0

我認爲您應該在調用存儲過程之後立即獲取結果值,然後將其存儲在某個會話變量中,您可以在第二個頁面後面的代碼執行時將其提取出來。 – Steve

0

得到它的 「secondPage.aspx」 你也可以使用OUTPUT INSERTEDexecute scalar

存儲過程

declare @idtbl table (id int) 
insert into Profile_Master(FirstName,LastName,Dob,Gender,MobileNo,Country, 
          State,EmailId,Password) 
output inserted.ID into @idtbl 
values 
(@FirstName,@LastName,@Dob,@Gender,@MobileNo,@Country,@State,@EmailId,@Password) 

SELECT id from @idtbl 

在C#代碼:

command.CommandText = "sp_name_here"; 
//add parameters 
command.CommandType = CommandType.StoredProcedure; 
var id = command.ExecuteScalar(); 
HttpContext.Current.Session["value"] = id.ToString() 
+0

更新了一次問題檢查。 –

+0

我的答案是不同於你在做什麼,檢查我的答案一次 –

+0

yaa但我這樣做,所以我知道爲什麼我得到一個空值? –