Your query is:
WHERE
Number LIKE ...
OR
CustomerName LIKE ...
OR
MobileNo LIKE ...
OR
SecMobileNo LIKE ...
OR
@SearchTerm = ''
AND
Status = @Status
Adding parentheses to match the implicit
operator precedence[
^] gives:
WHERE
Number LIKE ...
OR
CustomerName LIKE ...
OR
MobileNo LIKE ...
OR
SecMobileNo LIKE ...
OR
(
@SearchTerm = ''
AND
Status = @Status
)
In other words, if the
Number
,
CustomerName
,
MobileNo
, or
SecMobileNo
match, the record will be included
regardless of the
Status
.
To override the operator precedence, you will need to explicitly add parentheses to your query:
WHERE
(
Number LIKE ...
OR
CustomerName LIKE ...
OR
MobileNo LIKE ...
OR
SecMobileNo LIKE ...
OR
@SearchTerm = ''
)
AND
Status = @Status
In code:
string query = "SELECT Number, CustomerName, MobileNo, SecMobileNo, Status FROM customer";
query += " WHERE (Number LIKE '%' + @SearchTerm + '%'";
query += " OR CustomerName LIKE '%' + @SearchTerm + '%'";
query += " OR MobileNo LIKE '%' + @SearchTerm + '%'";
query += " OR SecMobileNo LIKE '%' + @SearchTerm + '%'";
query += " OR @SearchTerm = '')";
query += "AND Status = @Status";
NB: It may be easier to see the query if you use a
verbatim string[
^]:
const string query = @"SELECT
Number,
CustomerName,
MobileNo,
SecMobileNo,
Status
FROM
customer
WHERE
(
Number LIKE '%' + @SearchTerm + '%'
Or
CustomerName LIKE '%' + @SearchTerm + '%'
Or
MobileNo LIKE '%' + @SearchTerm + '%'
Or
SecMobileNo LIKE '%' + @SearchTerm + '%'
Or
@SearchTerm = ''
)
And
Status = @Status
";