5

考虑一个看起来像这样的查询:


my $query=<<QUERY;

select * from foo1 where col < ?
union all
select * from foo2 where col < ?
QUERY

假设实际查询确实需要联合,并且无法通过其他方式有效解决。where 子句中的变量将始终相同。有什么方法可以构造它,以便我只需要传递 1 个参数来执行,而不是传递相同的参数两次?

4

3 回答 3

5

可以尝试以下方法,我假设您将整数传递给 where 子句...

DECLARE @variableName as int

SET @variableName = ? --the value gets passed here once

select * from foo1 where col < @variableName -- and gets used here
union all
select * from foo2 where col < @variableName -- and here!
于 2012-05-10T18:09:54.090 回答
4

You could use the list repetition operator.

$sth->execute(($value) x 2);
于 2012-05-11T09:09:24.107 回答
4

在“真实”数据库中,您可以参数化查询并将查询作为参数传递。这是一个替代解决方案:

with const as (select ? as val)
select *
from ((select foo1.*
       from foo1 cross join const
       where col < const.val
      ) union all
      (select foo2.*
      from foo2 cross join const
      where col < const.val
     )) t

我并不是说这一定是个好主意。但是,我有时发现将参数收集到这样的子查询中然后在需要的地方加入它们非常有用。

于 2012-05-10T17:59:10.647 回答