Perl:如何使用 perl 将数据从 SQL 服务器导出到制表符分隔的 txt 文件

Perl: how to export data from SQL Server into tab delimited txt file using perl

我正在编写一个连接到 SQL 服务器的 perl 脚本。我编写了一个查询来获取我需要的数据。但是在 perl 中,如何使用 perl 将数据从 SQL 导出到制表符分隔的 txt 文件中?

这是我的示例脚本:

my $sql = "SELECT top (20) [code] AS Code
      ,Replace(Replace(Replace(Replace(Replace(Replace(Replace
      (Replace(Replace(Replace(Replace
      ([name],'\“','\"'),'\”','\"'),'<= ','&le;'),'>=','&ge;'),'<','&lt;'),'>','&gt;'),CHAR(10),'<br>'),'\n',' '),CHAR(13),' '),'–','-'),'’',''+NCHAR(39)+'') AS ShortDesc
      ,Replace(Replace(Replace(Replace(Replace(Replace(Replace
      (Replace(Replace(Replace(Replace
      ([description],'\“','\"'),'\”','\"'),'<= ','&le;'),'>=','&ge;'),'<','&lt;'),'>','&gt;'),CHAR(10),'<br>'),'\n',' '),CHAR(13),' '),'–','-'),'’',''+NCHAR(39)+'') AS LongDesc
      ,CASE WHEN isobsolete = 0 THEN 'NULL' ELSE 'Y' END AS Obsolete
      
FROM (
     SELECT ROW_NUMBER() OVER(PARTITION BY code ORDER BY effectivefromdate DESC) rn, * 
     FROM [CodingSuite_STG].[Codes].[Hcpcs] ) cs
     WHERE  rn=1 
     order by code asc";
     
my $sth = $dbh->prepare( $sql );

 
#Execute the statement
$sth->execute();


while ( my @row = $sth->fetchrow_array ) {
     print "@row\n";
}

#Close the connection
$sth->finish();
$dbh->disconnect();

您可以尝试使用join()。大致如下:

...

my $fh;

if (!open($fh, '>', "/path/to/file")) {
  die($!);
}

while (my @row = $sth->fetchrow_array) {
  print($fh, join("\t", @row) . "\n");
}

close($fh);

...