简体   繁体   English

无法将null传递给存储过程

[英]Cannot pass null to stored procedure

I am trying to execute a stored proc defined as such: 我正在尝试执行这样定义的存储过程:

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)

And I am calling it from code like this: 我从这样的代码中调用它:

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

But I am getting this error: 但我收到此错误:

The parameterized query '(@employeeId nvarchar(4000),@userName nvarchar(7),@firstName nva' expects the parameter '@employeeId', which was not supplied. 参数化查询'((@employeeId nvarchar(4000),@ userName nvarchar(7),@ firstName nva')需要未提供的参数'@employeeId'。

Why does the database care if the employee Id is null? 如果雇员ID为空,数据库为什么要关心呢?

EDIT: 编辑:

I forgot to mention a very important detail: even if @employeeId is populated, in this case, let's say with the value 54 , it will throw the same complaint, yet it will execute just fine through a SQL prompt. 我忘了提到一个非常重要的细节:即使填充了@employeeId ,在这种情况下,我们假设值54也会引发相同的投诉,但通过SQL提示符执行起来就很好。

You can pass a null, but it must be a DBNull. 您可以传递null,但必须为DBNull。

command.Parameters.AddWithValue("@employeeId", employeeId ?? DBNull.Value);

Hope this helps. 希望这可以帮助。

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

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