Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi - I'm trying to bind variables to an SQL statement. The statement must either return all records for one given number, or many records for many numbers using a wildcard such as '%'. If a number is provided then the statement works with '... organization_code = ? ...' If no number is provided then the statement needs to pass only the '%' wildcard - this is where I'm stuck. I have tried ' ... organization_code like ? ... and passed '%' with no luck. I am however able to pass '352%' and it binds correctly. I have also tried not binding anything if a number is not provided but it doesn't seem to like that because the bind is already set up to happen sometimes. Any help is appreciated.

Replies are listed 'Best First'.
Re: Wildcard variable bind?
by jhourcle (Prior) on Jan 21, 2009 at 22:40 UTC

    You occasionally have to write different SQL depending on the situation. I use the following code to basically build up the SQL query, and keep track of the values I'm going to need to bind. (it's a little more abstracted than you probably need -- I have multiple search engines that use this module):

    sub _AddSQL { my ($self, $sql, @bindvars) = @_; push @{$self->{'where'}}, $sql; push @{$self->{'bind'}}, @bindvars; } ... sub _SendSearch { my $self = shift; my $dp = $self->dataprovider(); my $db = $dp->GetDatabase() or return $self->_ThrowError('500 Database unavailable'); my $where = 'AND ('. join ( ') and (', @{$self->{'where'}}). +') '; ... my $sql = $dp->sql_prefix() . $where . $dp->sql_suffix(); $sth = $db->prepare( $sql ) or return $self->_ThrowError ( '500 Cannot prepare sea +rch', debug => $db->errstr ); $sth->execute( @{$self->{'bind'}} ) or return $self->_ThrowError ( '500 Cannot execute sea +rch', debug => $db->errstr ); my %fields; $sth->bind_columns( \(@fields{ @{ $sth->{'NAME_lc'} } } ) ); my @records = (); while ( $sth->fetch() ) { push @records, $self->_ProcessRecord( \%fields ); } return $self->dataprovider()->_PackageResults ( $numFound, \@r +ecords, debug => $where ); }

    The code that inherits it defines a series of handlers for different search terms, eg:

    (and crap -- would you believe, by posting this, I noticed a logic error in the code ... if 'wavetype' was defined, I wasn't processing the range match)