use Win32::OLE;
use Win32::OLE::Const ('Microsoft ActiveX Data Objects 2.6 Library');

#note adCmdText is imported by the above Const line, along with all the other constants found in this Class

#my $dsn = "DRIVER={SQL Server};SERVER=$server;APP=$appname;UID=$user;PWD=$pass;DATABASE=$db;";
#
# another possible DSN, but this is just one..  This should allow connectivity to MS SQL, Oracle, 
#     Informix, etc providing the right ODBC drivers are installed to allow such connectivity.

my $dsn = "DRIVER={SQL Server};SERVER=SOMESQLSERVER;APP=myPerlScript;DATABASE=master;trusted_connections=yes;";

call_sql($dsn,"select name,id from sysobjects",$records);

if (Win32::OLE->LastError() != 0) {
  die 0;
}
while (!$records->{EOF}) {
  print $records->Fields("name")->{Value}." - ".$records->Fields("id")->{Value}."\n";
  $records->{MoveNext};
  if ($records->{EOF}) {
    loop;
  }
}

sub call_sql {
  my $query = $_[1];

  my $dsn = $_[0];
  my $recordset;
    
  my $Conn = Win32::OLE->new("ADODB.Connection");
  if (Win32::OLE->LastError() != 0) {
    print "Failed creating ADODB.Connection object -> ".  Win32::OLE->LastError()."\n";
    return 0;
  }
  $Conn->{ConnectionTimeout} = 15;
  $Conn->{Open} = $dsn;

  if (Win32::OLE->LastError() != 0) {
    print "Failed opening ADODB.Connection object with DSN -> ".  Win32::OLE->LastError()."\n";
    return 0;
  }
  my $Cmd = Win32::OLE->new("ADODB.Command");
  if (Win32::OLE->LastError() != 0) {
    print "Failed creating ADODB.Command object -> ".Win32::OLE->LastError()."\n";
    return 0;
  }
  $Cmd->{CommandText} = $query;
  $Cmd->{CommandType} = adCmdText;
  $Cmd->{ActiveConnection} = $Conn;
  $Cmd->{Prepared} = 1;
  $Cmd->{CommandTimeout} = 45;#seconds to wait for query
  $RS = $Cmd->Execute();

  if (Win32::OLE->LastError() != 0) {
    print "Failed opening ADODB.Recordset object for Command -> (".Win32::OLE->LastError().")\n";
    return 0;
  } else {
    $_[2] = $RS;
    return 1;
  }
}
