sql查询字符串中的可选变量

时间:2013-08-28 22:19:12

标签: mysql sql database oracle

我正在自动化excel,我有一个字符串,我从表中读取输入为Variable1,2,3,4,5,6

如果它们保持空,查询按常规执行

,我希望将它们设为可选项
  SELECT LEFT(Name, 5) 
  FROM Production.Product
  where 
  product.name like 'Variable1'
  product.brand like 'Variable2'
  prodcut.price > 'Variable3'
  prodcut.expirydate > 'Variable4'
  ORDER BY ProductID;

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT LEFT(Name, 5) 
FROM Production.Product
WHERE
(Product.name like @Variable1 or @Variable1 IS NULL) AND
(Product.brand like @Variable2 or @Variable2 IS NULL) AND
(Product.price > @Variable3 or @Variable3 IS NULL) AND
(Product.expirydate > @Variable4 or @Variable4 IS NULL)
ORDER BY ProductID;

答案 1 :(得分:0)

以下查询应该可以解决问题:

SELECT LEFT(Name, 5) 
FROM Production.Product
WHERE
  ('Variable1' = '' OR product.name LIKE 'Variable1') AND
  ('Variable2' = '' OR product.brand LIKE 'Variable2') AND
  ('Variable3' = '' OR prodcut.price > 'Variable3') AND
  ('Variable4' = '' OR prodcut.expirydate > 'Variable4')
ORDER BY ProductID;

然而,您的查询看起来并不健康。可能在MySQL和MSSQL上运行的一个看起来像:

SELECT LEFT(Name, 5) 
FROM Production.Product
WHERE
  (@Variable1 = '' OR product.name LIKE @Variable1) AND
  (@Variable2 = '' OR product.brand LIKE @Variable2) AND
  (@Variable3 = '' OR prodcut.price > @Variable3) AND
  (@Variable4 = '' OR @Variable4 IS NULL OR prodcut.expirydate > @Variable4)
ORDER BY ProductID;

但是,您首先必须确定可能仍会更改查询的变量的数据类型,并且您还必须将'*'和/或'%'通配符添加到您正在投掷的字符串中或者它没有多大意义,'='会快得多。

希望这有帮助。

干杯