Jenda has asked for the wisdom of the Perl Monks concerning the following question:

I have code like this

sub DBCC { my $database = shift(); my $text = ''; my $dbh = DBI->connect('dbi:ODBC:jobodbc2', 'xxxx', 'xxxx', {PrintError => 0,RaiseError => 1,LongReadLen => 65536, odbc_async_exec => 1, odbc_err_handler => sub { my ($state, $msg) = @_; # Strip out all of the driver ID stuff $msg =~ s/^(\[[\w\s]*\])+//; $text .= $msg."\n"; return 0; } }); my $sth = $dbh->prepare("dbcc CHECKDB ('$database')"); $sth->execute; $dbh->disconnect(); return $text; }
to run the DBCC CHECKDB and capture the messages. It works perfect. I'd like to do the same thing for a stored procedure (some daily database maintenance task) that prints some headings and the counts of rows affected when run via the Query Analyzer, but can't seem to be able to do so. If I replace the "dbcc CHECKDB ('$database')" by "EXEC dbo.dbAdm_Daily" I get
DBD::ODBC::st execute failed: (DBD: dbd_describe/SQLNumResultCols err= +-1)

The procedure works when started from QueryAnalyzer and prints the messages. It works as well if called with $dbh->do(), but the messages are not captured in this case. What am I doing wrong?

Replies are listed 'Best First'.
Re: DBI+MS SQL, capture prints from stored procedures
by mikasue (Friar) on Apr 24, 2006 at 14:52 UTC
    Hi Jenda. Should "EXEC dbo.dbAdm_Daily" be "dbcc EXEC dbo.dbAdm_Daily"?? I don't know anything about this but seems the syntax for calling EXEC may not be consistent with how you are calling CHECKDB.
    Is the problem with CHECKDB or EXEC? This is not clear.

      Nope. DBCC CHECKDB ... is a builtin statement of MS SQL Server used to check the status of a database, while the dbo.dbAdm_Daily is a stored procedure and stored procedures should be executed using the EXEC keyword (you do not have to use the EXEC, but only if the procedure call is the very first statement in a batch.

      I just tried to call the procedure without the EXEC ... did not make any difference.

      In either case both the commands work just fine in Query Analyzer, both execute using $dbh->do(...), but I have to use the prepare+execute to be able to capture the messages and that only works for the DBCC command. God only knows why :-(

        Just a guess.. Does that SP only print and not return data? Maybe DBI doesn't currently behave correctly under those conditions and you need to return a 1x1 result.

        mhoward - at - hattmoward.org