2

I have a .sql file which contains multiple SQL statements. I need to loop over each statement and execute them from a Perl script. The problem is that the SQL statements are multiline statements and they include comments.

Up until now, we used the sqlplus command manually. But now we need to automate it to execute every statement and capture the success or failure of each statement. If a statement fails, I need to stop executing SQL statements from the file. As far I know, this isn't possible with sqlplus; it goes on executing the remaining statements after one of the statement fails.

The .sql file looks as below....

--Add new columns to TABLE_NAME table

ALTER TABLE "DATA"."TABLE_NAME" ADD(NAME varchar2(30));

--Create new table FILE_4G_TABLE

CREATE TABLE "DATA"."FILE_4G_TABLE"
(

 abc VARCHAR2(30 CHAR),

 def NUMBER(38),

 ghi NUMBER,

 JKL VARCHAR(32)

CONSTRAINT "FILE_4G_TABLE" PRIMARY KEY ("abc")) TABLESPACE "DATA";

Someone, please guide me.

4
  • So you want to parse SQL. Try SQL::Statement. Commented Dec 28, 2016 at 6:22
  • What flavour of SQL is being used? (For which database server?) Commented Dec 28, 2016 at 6:24
  • oracle data base.I am using DBI for it. Commented Dec 28, 2016 at 8:18
  • 1
    How you communicate with the database is of no importance. You're not trying to do that; you're trying to parse SQL statements. Commented Dec 28, 2016 at 8:19

2 Answers 2

1

Parse the sql file and push all statements in an array, then loop over the array and use DBI to prepare and execute the statements. SQL::Statement might be helpful as suggested by ikegami.

Sign up to request clarification or add additional context in comments.

Comments

0

Presupposing your SQL file is not huge, something like this might work. I'm making a huge leap here that splitting by ';' is enough to separate statements. If you had a ';' in a comment or within a literal, that would pretty much mess things up.

use strict;

use DBI;
use DBD::Oracle;

my $dbh = DBI->connect('dbi:Oracle:MyOracleService', 'user', 'password');

$/ = undef;
open my $IN, '<', 'test.sql' or die;
my $sql = <$IN>;
close $IN;

foreach my $mini_sql (split /;/, $sql) {
  $dbh->do($mini_sql);
}

$dbh->disconnect;

Also, this example was Oracle... if your DBMS is something else... well, you know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.