Hi,
I am trying to construct a flexible update SQL so that I can just pass the parameters that I want and it will construct the update SQL correctly for me. I have the code below.
#!/usr/bin/perl
use warnings;
use strict;
update_table( 'test_name', 'test_phone',
'test_city', 'test_country' );
update_table( 'test_name', 'test_phone',
'', 'test_country' );
update_table( 'test_name', '',
'test_city', '' );
sub update_table {
my ($name, $phone, $city, $country) = @_;
my $sql = qq! UPDATE table SET !
. qq! phone = '$phone', !
. qq! city = '$city', !
. qq! country = '$country' !
. qq! WHERE name = '$name' !;
print $sql;
return 1;
}
If I pass all the parameters to the subroutine, it gives me the correct update SQL. The problem starts when I start passing some null parameters.
For example, if I start passing some null parameters, the subroutine would create it like this:
UPDATE table SET phone = 'test_phone',
city = '', country = 'test_country' FROM ...
The correct one that I am hoping for is this (without the city assuming that I pass a null value for this parameter):
UPDATE table SET phone = 'test_phone',
country = 'test_country' FROM ...
So, to summary the problems:
How can I pass one or more null parameters to my subroutine and it will not add it in the SQL that it will create?
The subroutine should also know how to place the comma otherwise it will not be able to create the correct SQL.
Thanks.