如何将sql结果写入csv文件

时间:2012-10-08 07:43:40

标签: perl sql-server-2008

我有两个表,如A和B.表A有列名。表B列有公司名称。

这是我的代码:

$query1 = "SELECT Name FROM A"; 
$query2 = "SELECT Company Name FROM B"; 

$statement1 = $connection->prepare($query1);    
$statement2 = $connection->prepare($query2);

$statement1->execute();
$statement2>execute();

while ( ($name) = $statement->fetchrow_array) {
    push (@Name, $name);    
} 
while ( ($companyname) = $statement->fetchrow_array) {
    push (@companyName, $companyname);  
}

open (FH, ">>Output.csv") or die "$!";

我需要在csv文件中写这样的数据

Name   CompanyName

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy

xxx     yyyy

1 个答案:

答案 0 :(得分:1)

您可以在SQL查询中使用JOIN执行此操作。您不需要执行两个SELECT语句。

'SELECT a.Name, b.CompanyName FROM A a JOIN B b ON a.MailId = b.MailId'

这是一个完整的例子:

#!/usr/bin/perl
use strict; use warnings;
use DBI;

my $dbh = DBI->connect("put:dsn:here");
my $sth = $dbh->prepare('SELECT a.Name, b.CompanyName FROM A a JOIN B b ON a.MailId = b.MailId');

open my $fh, '>>', 'Output.csv' or die "Could not open file Output.csv: $!";
print $fh qq{Name\tCompanyName\n};

$sth->execute;
while (my $res = $sth->fetchrow_hashref) {
  print $fh qq{$res->{'Name'}\t$res->{'CompanyName'}\n};
}
close $fh;