Use named parameters:
#!/usr/bin/perl use warnings; use strict; update_table( name => 'test_name', phone => 'test_phone', city => 'test_city', country => 'test_country' ); update_table( name => 'test_name', phone => 'test_phone', country => 'test_country' ); update_table(name => 'test_name', city => 'test_city'); sub update_table { my (%params) = @_; die "name parameter is required by update_table ()\n" if !exists $params{name}; my @fieldNames = grep {$_ ne 'name'} keys %params; my @fields = map {"$_ = *"} @fieldNames; my $sql = "UPDATE table SET "; my @values = (@params{@fieldNames}, $params{name}); $sql .= join ', ', @fields; $sql .= " WHERE name = '*'"; print "$sql [values are @values]\n"; return 1; }
Prints:
UPDATE table SET country = *, city = *, phone = * WHERE name = '*' [va +lues are test_country test_city test_phone test_name] UPDATE table SET country = *, phone = * WHERE name = '*' [values are t +est_country test_phone test_name] UPDATE table SET city = * WHERE name = '*' [values are test_city test_ +name]
Note too that this uses place holders which should always be used to avoid quoting issues (and injection attacks for untrusted data sources).
In reply to Re: Flexible Update SQL
by GrandFather
in thread Flexible Update SQL
by bichonfrise74
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |