0

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

$p="All" 然后 buildingname in(Select buildingname from Building) else buildingname="$p"

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

4

3 回答 3

3

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

SELECT *
  FROM sometable
 WHERE (    :bind_variable = 'All' 
        AND buildingname IN (SELECT buildingname
                              FROM building))
     OR buildingname = :bind_variable
于 2012-08-08T15:20:55.597 回答
0

您可以在子查询中使用 OR,因此如果 $p 是“全部”,它要么选择建筑物选择,要么选择全部

buildingname in (Select buildingname from Building WHERE buildingname = $p OR $p = 'All')
于 2012-08-08T15:21:25.480 回答
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
}
于 2012-08-08T20:20:22.890 回答