简体   繁体   English

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

[英]SQL Server stored procedure if exists

Ideally, I'm trying to get a stored procedure to return 1 if exists, or 0 if not. 理想情况下,我尝试获取一个存储过程以返回1(如果存在)或0(如果不存在)。

This is the stored procedure: 这是存储过程:

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

Here's the code calling the stored procedure: 这是调用存储过程的代码:

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

Problem is that I am getting an error 问题是我遇到错误

Object reference not set to an instance of an object 你调用的对象是空的

on the return line of the calling code. 在调用代码的返回行上。

Any help would be greatly appreciated 任何帮助将不胜感激

As documeneted in officeil site 由于办公场所的文件

The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. 结果集中第一行的第一列;如果结果集为空,则为空引用(在Visual Basic中为Nothing)。 Returns a maximum of 2033 characters. 最多返回2033个字符。

ExecuteScalar returns null if no records were returned by the query 如果查询未返回任何记录,则ExecuteScalar返回null

So this line: 所以这行:

return (int)sqlCommand.ExecuteScalar(); 返回(int)sqlCommand.ExecuteScalar();

throws error 引发错误

becaue it is trying to cast null to an int in that case. 因为在这种情况下,它试图将null转换为int。 That'll raise a NullReferenceException. 这将引发NullReferenceException。

you need to check for null: 您需要检查是否为空:

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

The value from RETURN can be handled by a SqlParameter with a .Direction = ParameterDirection.ReturnValue . RETURN的值可以由带有.Direction = ParameterDirection.ReturnValueSqlParameter处理。 The value that .ExecuteScalar() will catch is a single row, single column returned by a SELECT in your stored procedure. .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