【问题标题】:Repeated arguments in a prepared statement准备好的语句中的重复参数
【发布时间】:2012-05-10 17:50:46
【问题描述】:

考虑如下所示的查询:


my $query=<<QUERY;

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

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

【问题讨论】:

    标签: sql perl dbi


    【解决方案1】:

    可以尝试以下方法,我假设您将整数传递给 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!
    

    【讨论】:

      【解决方案2】:

      您可以使用列表重复运算符。

      $sth->execute(($value) x 2);
      

      【讨论】:

        【解决方案3】:

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

        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
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-05-29
          • 1970-01-01
          • 1970-01-01
          • 2015-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多