I wrote this code out of a need to be able to quickly create copies of a database where security restrictions meant it was impossible to do a standard backup. This small snippet of code that can be used to.... 1, build a BCP export batch file, save it and run it 2, build a BCP import file and save it for later use Server names, user accounts, passwords will need to be added, It's (hopefully) obvious in the code where these changes are nneded A pre-requisite for this code to work is the SQL Server client and perl module "Win32::SqlServer"
#!/usr/local/bin/perl -w use strict; # important for variables use warnings; # Gives optional warnings use Win32::SqlServer qw(SCALAR); # This is thr module which is used +to connect to the RDBMS use IO::File; # File input output module use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); # Create database connection object, set database and then connect wit +h integrated security. my $sqlsrv = Win32::SqlServer->new; # Create a new SQLSRV object $sqlsrv->setloginproperty('Server', 'REPLACE_WITH_SERVER_NAME'); # Set + the Server property $sqlsrv->setloginproperty('Database', 'REPLACE_WITH_DATABASE_NAME'); # + Set the database property $sqlsrv->setloginproperty('Password', 'REPLACE_WITH_PASSWORD'); $sqlsrv->setloginproperty('Username', 'REPLACE_WITH_USERID'); $sqlsrv->connect(); # This is where we connect to the sql server syste +m using integrated security my $name; my $out = "outfile.cmd"; my $in = "infile.cmd"; my $nameout; + my $namein; my $stmnt01 = <<SQLEND; select 'bcp "REPLACE_WITH_SOURCE_DATABASE_NAME.dbo.' + name + '" out +"' + name + '_out.txt" -SREPLACE_WITH_SOURCE_SERVER_NAME -UREPLACE_WI +TH_USER_NAME -PREPLACE_WITH_PASSWORD -N' from sysobjects where type = + 'U' SQLEND my $stmnt02 = <<SQLEND; select 'bcp "REPLACE_WITH_DESTINATION_DATABASE_NAME.dbo.' + name + '" + in "' + name + '_out.txt" -SREPLACE_WITH_DESTINATION_SERVER_NAME -UR +EPLACE_WITH_USER_NAME --PREPLACE_WITH_PASSWORD -N' from sysobjects wh +ere type = 'U' SQLEND open (OUTFILE,">$out") or die "Can not open file $out for writing, qui +tting\n"; my $resultout = $sqlsrv->sql($stmnt01, SCALAR); foreach $nameout (@$resultout) { print OUTFILE "$nameout\n"; } open (INFILE,">$in") or die "Can not open file $in for writing, quitti +ng\n"; my $resultin = $sqlsrv->sql($stmnt02, SCALAR); foreach $namein (@$resultin) { print INFILE "$namein\n"; } close (OUTFILE); close (INFILE); system ("outfile.cmd");

Replies are listed 'Best First'.
Re: Cool usage for BCP/SQLServer
by Anonymous Monk on Sep 14, 2013 at 10:42 UTC

    As the author of Win32::SqlServer, I like to point out that the sample is completely confused. $sqlsrv->sql() is for running SQL commands. BCP is a command-line command, which you should run through system(). And you don't need to have Win32::SqlServer if that is all you want to do.