2014-06-06 143 views
0

理想情況下,我試圖讓存儲過程返回1(如果存在),否則返回0。SQL Server存儲過程(如果存在)

這是存儲過程:

CREATE PROCEDURE [dbo].[spCheckForExistingTimecard] 
    @userId int, 
    @paYPeriodId int, 
    @exists bit = 0 OUTPUT 
AS 
BEGIN 
    IF EXISTS (SELECT COUNT (t.TimeCardId) 
       FROM TimeCard AS t 
       WHERE t.PayPeriodId = @payPeriodId 
       AND t.UserId = @userId) 
     RETURN 1 
    ELSE 
     RETURN 0 

這裏是調用存儲過程的代碼:

public static int CheckForExistingTimecard(int userId, int payPeriodId) 
{ 
     using (SqlConnection connection = new SqlConnection(dbMaintenanceConnectionString)) 
     { 
      connection.Open(); 

      using (SqlCommand sqlCommand = new SqlCommand("spCheckForExistingTimecard", connection)) 
      { 
       sqlCommand.CommandType = CommandType.StoredProcedure; 
       sqlCommand.Parameters.AddWithValue("@userId", userId); 
       sqlCommand.Parameters.AddWithValue("@payPeriodId", payPeriodId); 
       return (int)sqlCommand.ExecuteScalar(); 
      } 
     } 
    } 

問題是,我得到一個錯誤不設置

對象引用到一個對象的實例

上的調用代碼的返回行。

任何幫助,將不勝感激

回答

1

正如officeil網站documeneted

第一行的結果集的第一列或空 引用(在Visual Basic中爲Nothing),如果結果集是空的。 返回最多2033個字符。如果沒有記錄被查詢

所以這條線返回

的ExecuteScalar返回null:

回報(INT)sqlCommand.ExecuteScalar();

拋出錯誤

becaue它試圖投空在這種情況下,一個int。這會引發NullReferenceException。

你需要檢查空:

object o = sqlCommand.ExecuteScalar(); 
item = o == null ? 0 : (int)o; 
1

RETURN值可以由SqlParameter.Direction = ParameterDirection.ReturnValue處理。 .ExecuteScalar()將捕獲的值是存儲過程中由SELECT返回的單列單列。

public static int CheckForExistingTimecard(int userId, int payPeriodId) 
{ 
    using (SqlConnection connection = new SqlConnection(dbMaintenanceConnectionString)) 
    using (SqlCommand sqlCommand = new SqlCommand("spCheckForExistingTimecard", connection)) 
    { 
     sqlCommand.CommandType = CommandType.StoredProcedure; 
     sqlCommand.Parameters.AddWithValue("@userId", userId); 
     sqlCommand.Parameters.AddWithValue("@payPeriodId", payPeriodId); 

     -- define your parameter for the RETURN value 
     sqlCommand.Parameters.Add("@ReturnValue").Direction = ParameterDirection.ReturnValue; 

     connection.Open(); 
     sqlCommand.ExecuteNonQuery(); 

     -- read the value returned 
     int returnValue = (int)sqlCommand.Parameters["@ReturnValue"]; 

     connection.Close(); 

     return returnValue; 
    } 
}