Search code examples
sql-serverperldbi

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


I am writing a perl script where it connect to SQL server. I've compose a query that will get the data that I need. But in perl, how can I export the data from SQL into tab delimited txt file using perl ?

here is my sample script:

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();

Solution

  • You can try and use join(). Something along the lines of:

    ...
    
    my $fh;
    
    if (!open($fh, '>', "/path/to/file")) {
      die($!);
    }
    
    while (my @row = $sth->fetchrow_array) {
      print($fh, join("\t", @row) . "\n");
    }
    
    close($fh);
    
    ...