繁体   English   中英

SQL Server存储过程(如果存在)

[英]SQL Server stored procedure if exists

理想情况下,我尝试获取一个存储过程以返回1(如果存在)或0(如果不存在)。

这是存储过程:

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();
            }
        }
    }

问题是我遇到错误

你调用的对象是空的

在调用代码的返回行上。

任何帮助将不胜感激

由于办公场所的文件

结果集中第一行的第一列;如果结果集为空,则为空引用(在Visual Basic中为Nothing)。 最多返回2033个字符。

如果查询未返回任何记录,则ExecuteScalar返回null

所以这行:

返回(int)sqlCommand.ExecuteScalar();

引发错误

因为在这种情况下,它试图将null转换为int。 这将引发NullReferenceException。

您需要检查是否为空:

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

RETURN的值可以由带有.Direction = ParameterDirection.ReturnValueSqlParameter处理。 .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;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM