我想知道如何在IF
语句中执行WHERE
语句,具体取决于@FirstName
和@LastName
的值(如果它是null
{ {1}}
这是我的代码:
SELECT tblCustomers.CustomerFirstName, tblCustomers.CustomerLastName FROm tblCustomers
where CustomerFirstName = @FirstName and CustomerLastName = @LastName
答案 0 :(得分:1)
我认为你正在寻找这个:
SELECT tblCustomers.CustomerFirstName, tblCustomers.CustomerLastName
FROM tblCustomers
WHERE CustomerFirstName = COALESCE(@FirstName, CustomerFirstName)
AND CustomerLastName = COALESCE(@LastName, CustomerLastName)
这样,如果参数为null,则where子句将忽略它 请注意,它不会返回列为空的任何行。
如果您的列可以为空并且您想要将它们为null的行重新归档,则需要使用Bennjoe Mordeno的答案中建议的where子句。
答案 1 :(得分:1)
Use CASE Statement in WHERE Clause :
SELECT tblCustomers.CustomerFirstName, tblCustomers.CustomerLastName
FROM tblCustomers
WHERE CustomerFirstName = CASE
WHEN ISNULL(@FirstName,'') <> '' THEN @FirstName ELSE CustomerFirstName END AND CustomerLastName = WHEN ISNULL(@LastName,'') <> '' THEN @LastName ELSE CustomerLastName END
答案 2 :(得分:0)
SELECT tblCustomers.CustomerFirstName, tblCustomers.CustomerLastName FROm tblCustomers
where (CustomerFirstName = @FirstName OR @FirstName IS NULL) and (CustomerLastName = @LastName OR @LastName IS NULL)
如果参数为null,则不必匹配列