无法将null传递给存储过程

jok*_*der 0 c# sql sql-server

我正在尝试执行如此定义的存储过程:

PROCEDURE [dbo].[SearchEmployees]
    @employeeId INT = NULL,
    @userName VARCHAR(50) = NULL,
    @firstName VARCHAR(50) = NULL,
    @lastName VARCHAR(50) = NULL

...
SELECT *
FROM Employee e
WHERE e.EmployeeId = @employeeId
    OR e.UserName LIKE(@userName)
    OR e.FirstName LIKE(@firstName)
    OR e.LastName LIKE(@lastName)
Run Code Online (Sandbox Code Playgroud)

我从这样的代码中调用它:

//employeeId = null, userName = "b.evans", firstName = "Bob", lastName = "Evans"
...
command.Parameters.AddWithValue("@employeeId", employeeId);
command.Parameters.AddWithValue("@userName", userName);
command.Parameters.AddWithValue("@firstName", firstName);
command.Parameters.AddWithValue("@lastName", lastName);
try
{
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            results.Add(mapper.Map(reader));
        }
    }
}
finally
{
    connection.Close();
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

参数化查询'(@ employeeId nvarchar(4000),@ userName nvarchar(7),@ firstName nva'需要参数'@employeeId',这是未提供的.

如果员工Id为空,数据库为什么要关心?

编辑:

我忘了提到一个非常重要的细节:即使@employeeId填充了,在这种情况下,让我们说这个值54,它会抛出相同的抱怨,但它会通过SQL提示执行得很好.

Dar*_*rek 6

您可以传递null,但它必须是DBNull.

command.Parameters.AddWithValue("@employeeId", employeeId ?? DBNull.Value);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 我其实不确定,但我依旧记得它应该是DBNull.Value. (3认同)
  • 或者在完全没有NULL的情况下传递任何东西并让默认值接管 (3认同)