Oracle SQL技巧

时间:2012-08-08 15:16:19

标签: sql oracle

我想在SQL查询的where子句中的oracle SQL中执行类似下面的操作

$ p =“全部”然后建筑名称(从建筑物中选择建筑物名称) 否则buildingname =“$ p”

问题是我无法解析这个$ p变量,即我无法检查它包含的内容

3 个答案:

答案 0 :(得分:3)

听起来你只想要一个OR条件,

SELECT *
  FROM sometable
 WHERE (    :bind_variable = 'All' 
        AND buildingname IN (SELECT buildingname
                              FROM building))
     OR buildingname = :bind_variable

答案 1 :(得分:0)

您可以在子查询中使用OR,因此如果$ p是'全部'它可以选择建筑物选择或全部选择。

buildingname in (Select buildingname from Building WHERE buildingname = $p OR $p = 'All')

答案 2 :(得分:0)

如果字符串中的变量被其包含的内容替换(因此它不是绑定变量,而只是来自PERL或PHP等语言的变量,并在您正在构建的选择字符串中使用):

$selectstring = "SELECT *
  FROM sometable
 WHERE (    '$p' = 'All' 
        AND buildingname IN (SELECT buildingname
                              FROM building))
     OR (   '$p' <> 'All' AND buildingname = '$p'"

意识到SQL注入的危险。绑定变量更好。无论如何,包含值'All'的变量$ p的语句将是

SELECT *
  FROM sometable
 WHERE (    'All' = 'All' 
        AND buildingname IN (SELECT buildingname
                              FROM building))
     OR (   'All' <> 'All' AND buildingname = 'All')

虽然你有一个包含变量$ p的选择字符串,其中包含

的'XYZ'
SELECT *
  FROM sometable
 WHERE (    'XYZ' = 'All' 
        AND buildingname IN (SELECT buildingname
                              FROM building))
     OR (   'XYZ' <> 'All' AND buildingname = 'XYZ')

但说实话,你也可以做点什么

if ($p eq 'All') {
...   one select
} else {
...   another select
}