可以在查询中多次绑定相同的值吗?

时间:2013-03-14 23:44:59

标签: sql perl sqlbindparameter

使用绑定参数似乎有某种(反?)模式:

$dbh->do(
       'select foo from bar where baz > ? and baz < ? + 1',
       undef,
       $var1, $var1
)

即。真正需要的是在查询中使用$var1两次的值。有没有办法避免在绑定参数列表中指定$var1两次?

3 个答案:

答案 0 :(得分:3)

首先,用法实际上是

$dbh->do(
       'select foo from bar where baz > ? and baz < ? + 1',
       undef,
       $var1, $var1
);

除非您的DBD支持positional or named placeholders

$dbh->do(
       'select foo from bar where baz > $1 and baz < $1 + 1',
       undef,
       $var1
);

你需要指定它两次,但你可以使用

$dbh->do(
       'select foo from bar where baz > ? and baz < ? + 1',
       undef,
       ($var1)x2
);

答案 1 :(得分:2)

一种方法是使用带编号的占位符,如果您的驱动程序支持它们,例如:

$dbh->do(
       'select foo from bar where baz > ?1 and baz < ?1 + 1',
       undef,
       $var1
)

答案 2 :(得分:1)

您要做的是使用命名参数。某些库如PDO support this