我有一个PostgreSQL数据库和一个Perl脚本,像这样
sub reassign_minions {
my $self = shift;
my @users = $self->get_userids_of_minions();
my $sth = $self->dbh->prepare(qq{update users set reports_to = ? where userid = ?});
$sth->execute($self->reports_to, $user);
$sth->finish;
}
假设 @users
保存一个包含多个用户id(整数)的数组。对于它返回的每个用户ID,我想用一个变量更新reports_to
列,但我不确定如何查询多个变量。
如果它只是一个,那就很容易了,因为我可以把变量参数设置成像上面那样的$userid
。但是由于可以传入的id的数量是不固定的,我不知道该怎么做。
我还被告知,有一种方法可以做到这一点,而不使用循环,因为我最初有一个for
循环。
使用IN
作为占位符
sub reassign_minions {
my $self = shift;
my @users = $self->get_userids_of_minions();
my $in = join ',', ('?') x @users;
my $sth = $self->dbh->prepare(qq{update users set reports_to = ? where userid IN ($in)});
$sth->execute($self->reports_to, @users) or die $self->dbh->errstr;;
$sth->finish;
}
Try This
my $sth = $self->dbh>prepare(qq{update users set reports_to = ? where userid = ?});
foreach my $user(@users) {
$sth->execute($self->reports_to, $user);
}
$sth->finish;