用于空参数的情况

时间:2017-03-15 08:57:44

标签: sql select parameters case

declare @customer varchar(50)

select cateogry, product_Name 
from product 
join order 
on product.id = order.product_id
join customer 
on order.customer_id = cutstomer.id 
where category = 'Tea'
and customer_name =
case 
when @customer is not null 
then @customer 
else 
'%'
end 

以上查询无法正常工作, 因为参数有时可能是空的。

2 个答案:

答案 0 :(得分:0)

=运算符不支持通配符。您应该使用like运算符:

SELECT category, product_Name 
FROM   product 
JOIN   order ON product.id = order.product_id
JOIN   customer ON order.customer_id = cutstomer.id 
WHERE  category = 'Tea' AND
       customer_name LIKE -- Here!
       CASE WHEN @customer IS NOT NULL THEN @customer 
       ELSE '%'
       END

或者,您可以使用or运算符将其短路:

SELECT category, product_Name 
FROM   product 
JOIN   order ON product.id = order.product_id
JOIN   customer ON order.customer_id = cutstomer.id 
WHERE  category = 'Tea' AND
       (@customer IS NULL OR customer_name = @customer)

答案 1 :(得分:0)

当参数不确定有值时使用

declare @customer varchar(50)

select cateogry, product_Name 
from product 
join order 
on product.id = order.product_id
join customer 
on order.customer_id = cutstomer.id 
where category = 'Tea'
and customer_name like
case 
when @customer is not null 
then @customer 
else 
'%'
end