Wednesday, July 1, 2015

Perl SQL query looping in Range of dates

Credited to http://stackoverflow.com/users/725418/tlp and http://stackoverflow.com/users/338059/sid-burn

http://stackoverflow.com/questions/19724688/perl-loop-through-months-in-a-specified-range

http://stackoverflow.com/questions/6622818/what-is-the-optimal-way-to-loop-between-two-dates-in-perl


# The Perl script below is trying to loop each day in a range of dates and perform SQL date query

#!/usr/bin/perl -w
use strict;

use Net::SSH::Any;
use DateTime;
use feature 'say';

my $hostname = "10.x.x.x";
my $username = "USER";

my $password = "PASS";

my $cmd = ""; 
my $output = "";

my $target_date = "";

my $start_date = DateTime->new(year => 2015, month => 1, day => 1);
my $end_date = DateTime->new(year=>2015, month => 7, day => 1);

my $ssh = Net::SSH::Any->new($hostname, user => $username, password => $password);
$ssh->error and die $ssh->error;

while ($start_date <= $end_date)
 {
# Get date format
say $start_date->strftime("%d-%b-%Y");
$target_date = $start_date->strftime("%d-%b-%Y");

# convert to uppercase for the month 
$target_date = uc $target_date;

# forming right SQL message
$cmd = "perl getSQLdata.pl \"SELECT  \\\"Project\\\" FROM \\\"Result\\\" where to_char(to_timestamp(\\\"Start_Time\\\",\'MM/DD/RRRR HH:MI:SS AM\'),\'DD-MON-RRRR\') = \'".$target_date."\'\"";
print $cmd;

# Get SQL data
$output = $ssh->capture($cmd);

# print output 
print $output."\n";

# increment a day
$start_date->add(days => 1);
}

exit 1;

No comments: