KnowledgeBase
PERL
Generate multiple SQL INSERT statements from CSV file
Generate multiple SQL INSERT statements from CSV file
This PERL script generates multiple SQL INSERT statements based on the contents of a CSV file
#!/usr/bin/perl
#======================================================================================
# gen_sql.pl by Mark Dowd of DowdTec Ltd - 26-Jan-2009
# Generate SQL INSERT statements from a CSV file
# ---------------------
# Parameters
# ==============
# tablename - Database table to insert into
# datafile - CSV file with headers
# ---------------------
#======================================================================================
use strict;
my $tablename = $ARGV[0];
open(INPUT, '<', "$ARGV[1]") or die "Can't open file: $!\n";
my $headline = <INPUT>;
chomp $headline;
my @header = split /,/, $headline;
for (<INPUT>) {
my (@lheader, @lvalue, $lheadstr, $lvalstr);
my @value = split /,/;
chomp @value;
for (my $i = 1; $i < @header; $i++) {
if ($value[$i-1]) {
push @lheader, $header[$i-1];
# If this is a slashed date...
if ($value[$i-1] =~ /(\d+)[-\/](\d+)[-\/](\d+)/) {
# ...use the Oracle "to_date" function to override the format
push @lvalue, "to_date('$value[$i-1]', 'DD/MM/YYYY')";
}
else {
# Trap embedded single quotes
$value[$i-1] =~ s/'/''/g;
push @lvalue, "'$value[$i-1]'";
}
}
}
$lheadstr = join(", ", @lheader);
$lvalstr = join(", ", @lvalue);
print "INSERT INTO $tablename\n($lheadstr)\nVALUES($lvalstr);\n";
}