my ($rtncd, $db) = OpenODBC($cfg{obtsdsn}, $cfg{dbf01}); my $colnames = ''; my $outfile = 'testfile.csv'; my $sqlstmt = ''; my @rowdata = (); open(OUTFILE, ">$outfile") || die "Could not open output file $outfile\n$!\n"; $colnames = join(',',@{GetColNames($db,$tblname)}); print OUTFILE $colnames."\n"; $sqlstmt = qq|SELECT TOP 10 * FROM $tblname|; if($db->Sql("$sqlstmt")){ $rtncd = -1; print "error!!Could not query table ". "$tblname\n$sqlstmt\n".$db->Error(); }else{ while($db->FetchRow()){ # retrieve and initialize data @rowdata = map{ $_ ||= '' } $db->Data(); # doesn't account for comma in data print OUTFILE join(',',@rowdata); print OUTFILE "\n"; # one per line } } close(OUTFILE); $db->Close; exit; } #end main() ############################################################; sub GetColNames{ my $db = shift; my $tblname = shift; my $rtncd = 0; my $sqlstmt = qq|SELECT TOP 1 * FROM $tblname|; my @colnames = (); if($db->Sql("$sqlstmt")){ $rtncd = -1; print "error!![0105]Could not query table ". "$tblname\n$sqlstmt\n".$db->Error(); }else{ if($db->FetchRow()){ push @colnames, $db->{fnames}[$_] for (0..$#{$db->{fnames}}); } } return \@colnames; } #end GetColNames() ############################################################;
In reply to Re: save the result of sql query in csv file
by periapt
in thread save the result of sql query in csv file
by shilpam
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |