2015-10-06 103 views
0

我想從存儲過程輸出,但在C#它給了我0.1爲什麼在c#級輸出參數返回0?

public short SelectOccupantTypesByOccupantTypeID(Int64 OccupantID) 
      { 

       SqlCommand SqlCom = new SqlCommand("SelectOccupantTypesByOccupantTypeID", DatabaseConnection.OpenConnection()); 
       SqlCom.CommandType = CommandType.StoredProcedure; 
       SqlCom.Parameters.AddWithValue("@pk_Occupants_OccupantID", OccupantID); 
       SqlParameter sqlParamOccupantTypeID = new SqlParameter("@OccupantTypeID", SqlDbType.SmallInt); 
       sqlParamOccupantTypeID.Direction = ParameterDirection.Output; 
       SqlCom.Parameters.Add(sqlParamOccupantTypeID); 
       short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value); 
       SqlCom.ExecuteNonQuery(); 
       DatabaseConnection.CloseConnection(); 

       return OccupantTypeID; 

      } 

試圖讓它

protected void ddlOccupants_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     Int64 OccupantID= Convert.ToInt64(ddlOccupants.SelectedValue); 
     Int16 OccupantTypeID= MngOccupants.SelectOccupantTypesByOccupantTypeID(OccupantID); 
     txtBoxMonthlyInstallment.Text = OccupantTypeID.ToString(); 

    } 

SP:

alter PROCEDURE [dbo].[SelectOccupantTypesByOccupantTypeID] 

    @pk_Occupants_OccupantID bigint, 
    @OccupantTypeID smallint output 

AS 
BEGIN 

     Set @OccupantTypeID= (Select Occupants.OccupantsOccupantTypeID 
     From Occupants 
     Where Occupants.pk_Occupants_OccupantID= @pk_Occupants_OccupantID) 

     return @OccupantTypeID 

END 

但SP返回正確的值在SQL級別但在C#級別返回0。爲什麼?

+10

您需要調用'ExecuteNonQuery' _before_您讀取值... – petelids

+0

仔細檢查您傳遞的參數並提取數據邏輯。如果DBMS說它返回零,它將返回零。確保使用配置文件工具。 – jean

+0

@jean這不一定是正確的。如果整數的值沒有被db調用覆蓋,它將返回默認值,對於整數類型,默認值爲0,這意味着petelids評論是答案。 –

回答

2

在執行查詢之前,您正在讀取參數的值,交換訂單。

SqlCom.ExecuteNonQuery(); 
short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value); 

但是你commiting等「陋習」,你的連接確實應該內using語句包裹和整個程序不重用。 ADO.NET已經實現了Connection Pooling,你不需要自己做,只需要根據需要進行短暫的連接,當你處理它們時,它們將返回到池中。

+0

謝謝,但這種做法從來沒有產生任何問題,因爲我的軟件在企業級運行多年沒有任何問題 – Covert

+2

然後,你有幸沒有一個程序,不斷拋出你的打開和關閉調用之間的異常,造成連接被打開但從不關閉耗盡與Sql Server的所有可用連接。至少我會建議你開始使用'try-finally'塊並將'DatabaseConnection.CloseConnection()'放在finally塊中。 –