具有多个空参数的查询不会返回正确的结果

时间:2014-04-08 20:23:55

标签: sql

我有一个搜索查询,其中有4个参数。用户可能提供一个参数或多个参数的值。 4个参数

FirstName, LastName, ssn, DateofBirth

我正在使用 -

Select * from person where 
(@FirstName is null or FirstName = @FirstName) Or ((@LastName is null or LastName = @LastName)
or
(@ssn is null or ssn = @ssn) Or ((@DateofBirth is null or DateofBirth = @DateofBirth)

在这种情况下,如果用户提供FirstName =" Sam"和LastName =" Paul"。我得到了所有的记录。我只是满足条件的行。喜欢FirstName =" Sam" LastName =" Gil",First Name =" Mike" LastName =" Paul"

1 个答案:

答案 0 :(得分:2)

您的条件之间需要And而不是Or

Select * from person where 
(@FirstName is null or FirstName = @FirstName) And (@LastName is null or LastName = @LastName)
And
(@ssn is null or ssn = @ssn) And (@DateofBirth is null or DateofBirth = @DateofBirth)

否则,只要任何参数为null,所有条件的整个Or链都将被计算为true。


更新:如果您想在条件之间保留Or,请尝试以下操作:

Select * from person where 
(@FirstName is not null And FirstName = @FirstName) Or (@LastName is not null And LastName = @LastName)
Or 
(@ssn is not null And ssn = @ssn) Or (@DateofBirth is not null And DateofBirth = @DateofBirth)

(内部条件更改为Andis nullis not null。)