Sybase::DBlib - Sybase DB-Library API


    use Sybase::DBlib;

    $dbh = Sybase::DBlib->new('user', 'pwd', 'server');
    $dbh->dbcmd("select * from master..sysprocesses");
    while($dbh->dbresults != NO_MORE_RESULTS) {
        while(@data = $dbh->dbnextrow) {
            print "@data\n";


Sybase::DBlib implements a subset of the Sybase DB-Library API. In general the perl version of the DB-Library calls use the same syntax as the C language version. However, in some cases the syntax (and sometimes, meaning) of some calls has been modified in order to make life easier for the perl programmer. It is a good idea to have the Sybase documentation for DB-Library handy when writing Sybase::DBlib programs. The documentation is available at

List of API calls

Standard Routines:

$dbh = new Sybase::DBlib [$user [, $pwd [, $server [, $appname [, {additional attributes}]]]]]
$dbh = Sybase::DBlib->dblogin([$user [, $pwd [, $server [, $appname, [{additional attributes}] ]]]])

Initiates a connection to a Sybase dataserver, using the supplied user, password, server and application name information. Uses the default values (see DBSETLUSER(), DBSETLPWD(), etc. in the Sybase DB-Library documentation) if the parameters are omitted.

The two forms of the call behave identically.

This call can be used multiple times if connecting to multiple servers with different username/password combinations is required, for example.

The additional attributes parameter allows you to define application specific attributes that you wish to associate with the $dbh.

NOTE: the connection to the database server that is associated with the $dbh that is created is automatically closed when the $dbh goes out of scope.

$dbh = Sybase::DBlib->dbopen([$server [, $appname, [{attributes}] ]])

Open an additional connection, using the current LOGINREC information.

$status = $dbh->dbuse($database)

Executes "use database $database" for the connection $dbh.

$status = $dbh->dbcmd($sql_cmd)

Appends the string $sql_cmd to the current command buffer of this connection.

$status = $dbh->dbsqlexec

Sends the content of the current command buffer to the dataserver for execution. See the DB-Library documentation for a discussion of return values.

$status = $dbh->dbresults

Retrieves result information from the dataserver after having executed dbsqlexec().

$status = $dbh->dbsqlsend

Send the command batch to the server, but do not wait for the server to return any results. Should be followed by calls to dbpoll() and dbsqlok(). See the Sybase docs for further details.

$status = $dbh->dbsqlok

Wait for results from the server and verify the correctness of the instructions the server is responding to. Mainly for use with dbmoretext() in Sybase::DBlib. See also the Sybase documentation for details.

($dbproc, $reason) = Sybase::DBlib->dbpoll($millisecs)
($dbproc, $reason) = $dbh->dbpoll($millisecs)

Note: The dbpoll() syntax has been changed since sybperl 2.09_05.

Poll the server to see if any connection has results pending. Used in conjunction with dbsqlsend() and dbsqlok() to perform asynchronous queries. dbpoll() will wait up to $millisecs milliseconds and poll any open DBPROCESS for results (if called as Sybase::DBlib->dbpoll()) or poll the specified DBPROCESS (if called as $dbh->dbpoll()). If it finds a DBPROCESS that is ready it returns it, along with the reason why it's ready. If dbpoll() times out, or if an interrupt occurs, $dbproc will be undefined, and $reason will be either DBTIMEOUT or DBINTERRUPT. If $millisecs is 0 then dbpoll() returns immediately. If $millisecs is -1 then it will not return until either results are pending or a system interrupt has occurred. Please see the Sybase documentation for further details.

Here is an example of using dbsqlsend(), dbpoll() and dbsqlok():

  $dbh->dbcmd("exec big_hairy_query_proc");
  # here you can go do something else...
  # now - find out if some results are waiting
  ($dbh2, $reason) = $dbh->dbpoll(100);
  if($dbh2 && $reason == DBRESULT) {   # yes! - there's data on the pipe
     while($dbh2->dbresults != NO_MORE_RESULTS) {
        while(@dat = $dbh2->dbnextrow) {
$status = $dbh->dbcancel

Cancels the current command batch.

$status = $dbh->dbcanquery

Cancels the current query within the currently executing command batch.


Free the command buffer (required only in special cases - if you don't know what this is you probably don't need it :-)


Force the closing of a connection. Note that connections are automatically closed when the $dbh goes out of scope.


Returns TRUE if the DBPROCESS has been marked DEAD by DB-Library.

$status = $dbh->DBCURCMD

Returns the number of the currently executing command in the command batch. The first command is number 1.

$status = $dbh->DBMORECMDS

Returns TRUE if there are additional commands to be executed in the current command batch.

$status = $dbh->DBCMDROW

Returns SUCCEED if the current command can return rows.

$status = $dbh->DBROWS

Returns SUCCEED if the current command did return rows.

$status = $dbh->DBCOUNT

Returns the number of rows that the current command affected.

$row_num = $dbh->DBCURROW

Returns the number (counting from 1) of the currently retrieved row in the current result set.

$spid = $dbh->dbspid

Returns the SPID (server process ID) of the current connection to the Sybase server.

$status = $dbh->dbhasretstat

Did the last executed stored procedure return a status value? dbhasretstats must only be called after dbresults returns NO_MORE_RESULTS, i.e. after all the select, insert, update operations of the stored procedure have been processed.

$status = $dbh->dbretstatus

Retrieve the return status of a stored procedure. As with dbhasretstat, call this function after all the result sets of the stored procedure have been processed.

$status = $dbh->dbnumcols

How many columns are in the current result set.

$status = $dbh->dbcoltype($colid)

What is the column type of column $colid in the current result set.

$type = $dbh->dbprtype($colid)

Returns the column type as a printable string.

$status = $dbh->dbcollen($colid)

What is the length (in bytes) of column $colid in the current result set.

$string = $dbh->dbcolname($colid)

What is the name of column $colid in the current result set.

@dat = $dbh->dbnextrow([$doAssoc [, $wantRef]])

Retrieve one row. dbnextrow() returns a list of scalars, one for each column value. If $doAssoc is non-0, then dbnextrow() returns a hash (aka associative array) with column name/value pairs. This relieves the programmer from having to call dbbind() or dbdata().

If $wantRef is non-0, then dbnextrow() returns a reference to a hash or an array. This reference points to a static array (or hash) so if you wish to store the returned rows in an array, you must copy the array/hash:

  while($d = $dbh->dbnextrow(0, 1)) {
     push(@rows, [@$d]);

The return value of the C version of dbnextrow() can be accessed via the Perl DBPROCESS attribute field, as in:

   @arr = $dbh->dbnextrow;              # read results
   if($dbh->{DBstatus} != REG_ROW) {
     take some appropriate action...

When the results row is a COMPUTE row, the ComputeID field of the DBPROCESS is set:

   @arr = $dbh->dbnextrow;              # read results
   if($dbh->{ComputeID} != 0) { # it's a 'compute by' row
     take some appropriate action...

dbnextrow() can also return a hash keyed on the column name:

   $dbh->dbcmd("select Name=name, Id = id from test_table");
   $dbh->dbsqlexec; $dbh->dbresults;

   while(%arr = $dbh->dbnextrow(1)) {
      print "$arr{Name} : $arr{Id}\n";
@dat = $dbh->dbretdata([$doAssoc])

Retrieve the value of the parameters marked as 'OUTPUT' in a stored procedure. If $doAssoc is non-0, then retrieve the data as an associative array with parameter name/value pairs.

$bylist = $dbh->dbbylist($computeID)

Returns the by list for a compute by clause. $bylist is a reference to an array of colids. You can use $dbh->dbcolname() to get the column names.

    $dbh->dbcmd("select * from sysusers order by uid compute count(uid) by uid");
    my @dat;
    while(@dat = $dbh->dbnextrow) {
        if($dbh->{ComputeID} != 0) {
            my $bylist = $dbh->dbbylist($dbh->{ComputeID});
            print "bylist = @$bylist\n";
        print "@dat\n";
%hash = $dbh->dbcomputeinfo($computeID, $column)

Returns a hash with the colid, op, len, type and utype of the compute by column. You can call this subroutine to get the information returned by DB-Library's dbalt*() calls. The $column is the column number in the current compute by row (starting at 1) and the $computeID is best retrieved from $dbh-{ComputeID}>. Please see the documentation of the dbalt*() calls in Sybase's DB-Library manual.

$string = $dbh->dbstrcpy

Retrieve the contents of the command buffer.

$ret = $dbh->dbsetopt($opt [, $c_val [, $i_val]])

Sets option $opt with optional character parameter $c_val and optional integer parameter $i_val. $opt is one of the option values defined in the Sybase DB-Library manual ( DBSHOWPLAN, DBTEXTSIZE). For example, to set SHOWPLAN on, you would use


See also dbclropt() and dbisopt() below.

$ret = $dbh->dbclropt($opt [, $c_val])

Clears the option $opt, previously set using dbsetopt().

$ret = $dbh->dbisopt($opt [, $c_val])

Returns TRUE if the option $opt is set.

$string = $dbh->dbsafestr($string [,$quote_char])

Convert $string to a 'safer' version by inserting single or double quotes where appropriate, so that it can be passed to the dataserver without syntax errors.

The second argument to dbsafestr() (normally DBSINGLE, DBDOUBLE or DBBOTH) has been replaced with a literal ' or " (meaning DBSINGLE or DBDOUBLE, respectively). Omitting this argument means DBBOTH.

$packet_size = $dbh->dbgetpacket

Returns the TDS packet size currently in use for this $dbh.


$status = $dbh->dbwritetext($colname, $dbh_2, $colnum, $text [, $log])

Insert or update data in a TEXT or IMAGE column. The usage is a bit different from that of the C version:

The calling sequence is a little different from the C version, and logging is off by default:

$dbh_2 and $colnum are the DBPROCESS and column number of a currently active query. Example:

   $dbh_2->dbcmd('select the_text, t_index from text_table where t_index = 5');
   $dbh_2->dbsqlexec; $dbh_2->dbresults;
   @data = $dbh_2->dbnextrow;

   $d->dbwritetext ("text_table.the_text", $dbh_2, 1,
        "This is text which was added with Sybperl", TRUE);
$status = $dbh->dbpreptext($colname, $dbh_2, $colnum, $size [, $log])

Prepare to insert or update text with dbmoretext().

The calling sequence is a little different from the C version, and logging is off by default:

$dbh_2 and $colnum are the DBPROCESS and column number of a currently active query. Example:

   $dbh_2->dbcmd('select the_text, t_index from text_table where t_index = 5');
   $dbh_2->dbsqlexec; $dbh_2->dbresults;
   @data = $dbh_2->dbnextrow;

   $size = length($data1) + length($data2);
   $d->dbpreptext ("text_table.the_text", $dbh_2, 1, $size, TRUE);
   $dbh->dbmoretext(length($data1), $data1);
   $dbh->dbmoretext(length($data2), $data2);

$status = $dbh->dbmoretext($size, $data)

Sends a chunk of TEXT/IMAGE data to the server. See the example above.

$status = $dbh->dbreadtext($buf, $size)

Read a TEXT/IMAGE data item in $size chunks.


    $dbh->dbcmd("select data from text_test where id=1");
    while($dbh->dbresults != NO_MORE_RESULTS) {
        my $bytes;
        my $buf = '';
        while(($bytes = $dbh->dbreadtext($buf, 512)) != NO_MORE_ROWS) {
            if($bytes == -1) {
                die "Error!";
            } elsif ($bytes == 0) {
                print "End of row\n";
            } else {
                print "$buf";

BCP Routines

See also the Sybase::BCP module.


This is an exported routine (i.e., it can be called without a $dbh handle) which sets the BCP IN flag to TRUE/FALSE.

It is necessary to call BCP_SETL(TRUE) before opening the connection with which one wants to run a BCP IN operation.

$state = bcp_getl

Retrieve the current BCP flag status.

$status = $dbh->bcp_init($table, $hfile, $errfile, $direction)

Initialize BCP library. $direction can be DB_OUT or DB_IN

$status = $dbh->bcp_meminit($numcols)

This is a utility function that does not exist in the normal BCP API. Its use is to initialize some internal variables before starting a BCP operation from program variables into a table. This call avoids setting up translation information for each of the columns of the table being updated, obviating the use of the bcp_colfmt call.

See EXAMPLES, below.

$status = $dbh->bcp_sendrow(LIST)
$status = $dbh->bcp_sendrow(ARRAY_REF)

Sends the data in LIST to the server. The LIST is assumed to contain one element for each column being updated. To send a NULL value set the appropriate element to the Perl undef value.

In the second form you pass an array reference instead of passing the LIST, which makes processing a little bit faster on wide tables.

$rows = $dbh->bcp_batch

Commit rows to the database. You usually use it like this:

       while(<IN>) {
           @data = split(/\|/);
           $d->bcp_sendrow(\@data);    # Pass the array reference

           # Commit data every 100 rows.
           if((++$count % 100) == 0) {
$status = $dbh->bcp_done
$status = $dbh->bcp_control($field, $value)
$status = $dbh->bcp_columns($colcount)
$status = $dbh->bcp_colfmt($host_col, $host_type, $host_prefixlen, $host_collen, $host_term, $host_termlen, $table_col [, $precision, $scale])

If you have DB-Library for System 10 or higher, then you can pass the additional $precision and $scale parameters, and have sybperl call bcp_colfmt_ps() instead of bcp_colfmt().

$status = $dbh->bcp_collen($varlen, $table_column)
$status = $dbh->bcp_exec
$status = $dbh->bcp_readfmt($filename)
$status = $dbh->bcp_writefmt($filename)

Please see the DB-Library documentation for these calls.

DBMONEY Routines

NOTE: In this version it is possible to avoid calling the routines below and still get DBMONEY calculations done with the correct precision. See the Sybase::DBlib::Money discussion below.

($status, $sum) = $dbh->dbmny4add($m1, $m2)
$status = $dbh->dbmny4cmp($m1, $m2)
($status, $quotient) = $dbh->dbmny4divide($m1, $m2)
($status, $dest) = $dbh->dbmny4minus($source)
($status, $product) = $dbh->dbmny4mul($m1, $m2)
($status, $difference) = $dbh->dbmny4sub($m1, $m2)
($status, $ret) = $dbh->dbmny4zero
($status, $sum) = $dbh->dbmnyadd($m1, $m2)
$status = $dbh->dbmnycmp($m1, $m2)
($status, $ret) = $dbh->dbmnydec($m1)
($status, $quotient) = $dbh->dbmnydivide($m1, $m2)
($status, $ret, $remainder) = $dbh->dbmnydown($m1, $divisor)
($status, $ret) = $dbh->dbmnyinc($m1)
($status, $ret, $remain) = $dbh->dbmnyinit($m1, $trim)
($status, $ret) = $dbh->dbmnymaxneg
($status, $ret) = $dbh->dbmnymaxpos
($status, $dest) = $dbh->dbmnyminus($source)
($status, $product) = $dbh->dbmnymul($m1, $m2)
($status, $m1, $digits, $remain) = $dbh->dbmnyndigit($m1)
($status, $ret) = $dbh->dbmnyscale($m1, $multiplier, $addend)
($status, $difference) = $dbh->dbmnysub($m1, $m2)
($status, $ret) = $dbh->dbmnyzero

All of these routines correspond to their DB-Library counterpart, with the following exception:

The routines which in the C version take pointers to arguments (in order to return values) return these values in a list instead:

   status = dbmnyadd(dbproc, m1, m2, &result) becomes
   ($status, $result) = $dbproc->dbmnyadd($m1, $m2)

RPC Routines

NOTE: Check out eg/ for an example on how to use these calls.

$dbh->dbrpcinit($rpcname, $option)

Initialize an RPC call to the remote procedure $rpcname. See the DB-Library manual for valid values for $option.

$dbh->dbrpcparam($parname, $status, $type, $maxlen, $datalen, $value)

Add a parameter to an RPC call initiated with dbrpcinit(). Please see the DB-Library manual page for details & values for the parameters.

NOTE: All floating point types (MONEY, FLOAT, REAL, DECIMAL, etc.) are converted to FLOAT before being sent to the RPC.


Execute an RPC initiated with dbrpcinit().

By default this routine calls the C library dbrpcsend() and dbsqlok(), so that you can directly call $dbh->dbresults directly after a call to $dbh->dbrpcsend. If you need more control you can pass a non-0 value for the $no_ok parameter, and it will then be your responsibility to call $dbh->dbsqlok(). Please read the Sybase OpenClient DB-Library manual pages on dbrpcsend() and dbsqlok() for further details.

dbrpwset($srvname, $pwd)

Set the password for connecting to a remote server.


Clear all remote server passwords.

Registered procedure execution

$status = $dbh->dbreginit($proc_name)
$status = $dbh->dbreglist
$status = $dbh->dbreglist($parname, $type, $datalen, $value)
$status = $dbh->dbregexec($opt)

These routines are used to execute an OpenServer registered procedure. Please see the Sybase DB-Library manual for a description of what these routines do, and how to call them.

Two Phase Commit Routines

$dbh = Sybase::DBlib->open_commit($user, $pwd, $server, $appname)
$id = $dbh->start_xact($app_name, $xact_name, $site_count)
$status = $dbh->stat_xact($id)
$status = $dbh->scan_xact($id)
$status = $dbh->commit_xact($id)
$status = $dbh->abort_xact($id)
$string = Sybase::DBlib::build_xact_string($xact_name, $service_name, $id)
$status = $dbh->remove_xact($id, $site_count)

Please see the Sybase documentation for this.

NOTE: These routines have not been thoroughly tested!

Exported Routines

$old_handler = dberrhandle($err_handle)
$old_handler = dbmsghandle($msg_handle)

Register an error (or message) handler for DB-Library to use. Handler examples can be found in in the Sybperl distribution. Returns a reference to the previously defined handler (or undef if none were defined). Passing undef as the argument clears the handler.


Set the name of the 'interfaces' file. This file is normally found by DB-Library in the directory pointed to by the $SYBASE environment variable.


Start recording all SQL sent to the server in file $filename.


Returns a string identifying the version of DB-Library that this copy of Sybperl was built with.

$time = dbsettime($seconds)
$time = dbsetlogintime($seconds)

These utility routines are probably very seldom used. See the DB-Library manual for an explanation of their use.


Tell DB-Library that we're done. Once this call has been made, no further activity requiring DB-Library can be performed in the current program.

High Level Wrapper Functions (sql() and nsql())

These routines are not part of the DB-Library API, but have been added because they can make our life as programmers easier, and exploit certain strengths of Perl.

$ret|@ret = $dbh->sql($cmd [, \&rowcallback [, $flag]])

Runs the sql command and returns the result as a reference to an array of the rows. In a LIST context, return the array itself (instead of a reference to the array). Each row is a reference to a list of scalars.

If you provide a second parameter it is taken as a procedure to call for each row. The callback is called with the values of the row as parameters.

If you provide a third parameter, this is used in the call to dbnextrow() to retrieve associative arrays rather than 'normal' arrays for each row, and store them in the returned array. To pass the third parameter without passing the &rowcallback value you should pass the special value undef as second parameter:

        @rows = $dbh->sql("select * from sysusers", undef, TRUE);
        foreach $row_ref (@rows) {
            if($$row_ref{'uid'} == 10) {

See also eg/ for an example.

Contributed by Gisle Aas.

NOTE: This routine loads all the data into memory. It should not be run with a query that returns a large number of rows. To avoid the risk of overflowing memory, you can limit the number of rows that the query returns by setting the 'MaxRows' field of the $dbh attribute field:

        $dbh->{'MaxRows'} = 100;

This value is not set by default.

@ret = $dbh->nsql($sql [, "ARRAY" | "HASH" ] [, \&subroutine ] );

An enhanced version of the sql routine, nsql, is also available. nsql() provides better error checking (using its companion error and message handlers), optional deadlock retry logic, and several options for the format of the return values. In addition, the data can either be returned to the caller in bulk, or processes line by line via a callback subroutine passed as an argument (this functionality is similar to the r_sql() method).

The arguments are an SQL command to be executed, the $type of the data to be returned, and the callback subroutine.

if a callback subroutine is not given, then the data from the query is returned as an array. The array returned by nsql is one of the following:

    Array of Hash References (if type eq HASH)
    Array of Array References (if type eq ARRAY)
    Simple Array (if type eq ARRAY, and a single column is queried)
    Boolean True/False value (if type ne ARRAY or HASH)

Optionally, instead of the words "HASH" or "ARRAY" a reference of the same type can be passed as well. That is, both of the following are equivalent:

    $dbh->nsql("select col1,col2 from table","HASH");
    $dbh->nsql("select col1,col2 from table",{});

For example, the following code will return an array of hash references:

    @ret = $dbh->nsql("select col1,col2 from table","HASH");
    foreach $ret ( @ret ) {
      print "col1 = ", $ret->{'col1'}, ", col2 = ", $ret->{'col2'}, "\n";

The following code will return an array of array references:

    @ret = $dbh->nsql("select col1,col2 from table","ARRAY");
    foreach $ret ( @ret ) {
      print "col1 = ", $ret->[0], ", col2 = ", $ret->[1], "\n";

The following code will return a simple array, since the select statement queries for only one column in the table:

    @ret = $dbh->nsql("select col1 from table","ARRAY");
    foreach $ret ( @ret ) {
      print "col1 = $ret\n";

Success or failure of an nsql() call cannot necessarily be judged from the value of the return code, as an empty array may be a perfectly valid result for certain sql code.

The nsql() routine will maintain the success or failure state in a variable $DB_ERROR, accessed by the method of the same name, and a pair of Sybase message/error handler routines are also provided which will use $DB_ERROR for the Sybase messages and errors as well. However, these must be installed by the client application:


Success of failure of an nsql() call cannot necessarily be judged from the value of the return code, as an empty array may be a perfectly valid result for certain sql code.

The following code is the proper method for handling errors with use of nsql.

    @ret = $dbh->nsql("select stuff from table where stuff = 'nothing'","ARRAY");
    if ( $DB_ERROR ) {
      # error handling code goes here, perhaps:
      die "Unable to get stuff from table: $DB_ERROR\n";

The behavior of nsql() can be customized in several ways. If the variable:


is true, then nsql() will strip the trailing white spaces from all of the scalar values in the results.

When using a callback subroutine, the subroutine is passed to nsql() as a CODE reference. For example:

    sub parse_hash {
      my %data = @_;
      # Do something with %data 

    $dbh->nsql("select * from really_huge_table","HASH",\&parse_hash);
    if ( $DB_ERROR ) {
      # error handling code goes here, perhaps:
      die "Unable to get stuff from really_huge_table: $DB_ERROR\n";

In this case, the data is passed to the callback (&parse_hash) as a HASH, since that was the format specified as the second argument. If the second argument specifies an ARRAY, then the data is passed as an array. For example:

    sub parse_array {
      my @data = @_;
      # Do something with @data 

    $dbh->nsql("select * from really_huge_table","HASH",\&parse_array);
    if ( $DB_ERROR ) {
      # error handling code goes here, perhaps:
      die "Unable to get stuff from really_huge_table: $DB_ERROR\n";

The primary advantage of using the callback is that the rows are processed one at a time, rather than returned in a huge array. For very large tables, this can result in very significant memory consumption, and on resource-constrained machines, some large queries may simply fail. Processing rows individually will use much less memory.

IMPORTANT NOTE: The callback subroutine must return a true value if it has successfully handled the data. If a false value is returned, then the query is canceled via dbcancel(), and nsql() will abort further processing.

WARNING: Using the following deadlock retry logic together with a callback routine is dangerous. If a deadlock is encountered after some rows have already been processed by the callback, then the data will be processed a second time (or more, if the deadlock is retried multiple times).

The nsql() method also supports automated retries of deadlock errors (1205). This is disabled by default, and enabled only if the variable


is non-zero. This variable is the number of times to resubmit a given SQL query, and the variable


is the delay, in seconds, between retries (default is 60). Normally, the retries happen silently, but if you want nsql() to carp() about it, then set


to a true value, and nsql() will whine about the failure. If all of the retries fail, then nsql() will return an error, as it normally does. If you want the code to try forever, then set the retry count to -1.


Most of the #defines from sybdb.h can be accessed as Sybase::DBlib::NAME (e.g., Sybase::DBlib::STDEXIT). Additional constants are:


The Sybperl version. Can be interpreted as a string or as a number.


The version of DB-Library that sybperl was built against.


The behavior of certain aspects of the Sybase::DBlib module can be controlled via global or connection specific attributes. The global attributes are stored in the %Sybase::DBlib::Att variable, and the connection specific attributes are stored in the $dbh. To set a global attribute, you would code

     $Sybase::DBlib::Att{'AttributeName'} = value;

and to set a connection specific attribute you would code

     $dbh->{"AttributeName'} = value;

NOTE!!! Global attribute setting changes do not affect existing connections, and changing an attribute inside a ct_fetch() does not change the behavior of the data retrieval during that ct_fetch() loop.

The following attributes are currently defined:


If set, NULL results are returned as the Perl 'undef' value, otherwise as the string "NULL". Default: set.


If set, numeric results are not converted to strings before returning the data to Perl. Default: set.


If set, BINARY results are preceded by '0x' in the result. Default: unset.


Turn the special handling of DATETIME values on. Default: unset. See the section on special datatype handling below.


Turn the special handling of MONEY values on. Default: unset. See the section on special datatype handling below.

Status Variables

These status variables are set by Sybase::DBlib internal routines, and can be accessed using the $dbh->{'variable'} syntax.


The return status of the last call to dbnextrow.


The compute id of the current returned row. Is 0 if no compute by clause is currently being processed.


BCP from program variables

See also Sybase::BCP for a simplified bulk copy API.

   $dbh = new Sybase::DBlib $User, $Password;
   $dbh->bcp_init("test.dbo.t2", '', '', DB_IN);
   $dbh->bcp_meminit(3);   # we wish to copy three columns into
                           # the 't2' table
        @dat = split(' ', $_);
   $ret = $dbh->bcp_done;
Using the sql() routine
   $dbh = new Sybase::DBlib;
   $ret = $dbh->sql("select * from sysprocesses");
   foreach (@$ret)   # Loop through each row
       @row = @$_;
       # do something with the data row...

   $ret = $dbh->sql("select * from sysusers", sub { print "@_"; });
   # This will select all the info from sysusers, and print it
Getting SHOWPLAN and STATISTICS information within a script

You can get SHOWPLAN and STATISTICS information when you run a sybperl script. To do so, you must first turn on the respective options, using dbsetopt(), and then you need a special message handler that will filter the SHOWPLAN and/or STATISTICS messages sent from the server.

The following message handler differentiates the SHOWPLAN or STATICSTICS messages from other messages:

    # Message number 3612-3615 are statistics time / statistics io
    # message. Showplan messages are numbered 6201-6225.
    # (I hope I haven't forgotten any...)
    @sh_msgs = (3612 .. 3615, 6201 .. 6225);
    @showplan_msg{@sh_msgs} = (1) x scalar(@sh_msgs);

    sub showplan_handler {
        my ($db, $message, $state, $severity, $text,
            $server, $procedure, $line) = @_;
        # Don't display 'informational' messages:
        if ($severity > 10) {
            print STDERR ("Sybase message ", $message, ",
               Severity ", $severity, ", state ", $state);
            print STDERR ("\nServer `", $server, "'") if defined ($server);
            print STDERR ("\nProcedure `", $procedure, "'")
                  if defined ($procedure);
            print STDERR ("\nLine ", $line) if defined ($line);
            print STDERR ("\n    ", $text, "\n\n");
        elsif($showplan_msg{$message}) {
        # This is a HOWPLAN or STATISTICS message, so print it out:
            print STDERR ($text, "\n");
        elsif ($message == 0) {
            print STDERR ($text, "\n");

This could then be used like this:

    use Sybase::DBlib;

    $dbh = new Sybase::DBlib  'mpeppler', $password, 'TROLL';

    $dbh->dbsetopt(DBSTAT, "IO");
    $dbh->dbsetopt(DBSTAT, "TIME");

    $dbh->dbcmd("select * from xrate where date = '951001'");
    while($dbh->dbresults != NO_MORE_RESULTS) {
        while(@dat = $dbh->dbnextrow) {
            print "@dat\n";

Et voilà!

Utility routines


Turns the debugging trace on or off. The value of $bitmask determines which features are going to be traced. The following trace bits are currently recognized:


    Trace all CTlib and/or DBlib object creations.


    Trace all calls to DESTROY.


    Traces all SQL language commands - (i.e. calls to dbcmd(), ct_execute() or ct_command()).


    Traces calls to dbresults()/ct_results().


    Traces calls to dbnextrow()/ct_fetch(), and traces the values that are pushed on the stack.


    Trace all overloaded operations involving DateTime, Money or Numeric datatypes.

Two special trace flags are TRACE_NONE, which turns off debug tracing, and TRACE_ALL which (you guessed it!) turns everything on.

The traces are pretty obscure, but they can be useful when trying to find out what is really going on inside the program.

For the TRACE_* flags to be available in your scripts, you must load the Sybase::DBlib module with the following syntax:

     use Sybase::DBlib qw(:DEFAULT /TRACE/);

This tells the autoloading mechanism to import all the default symbols, plus all the trace symbols.

Special handling of DATETIME, MONEY & NUMERIC/DECIMAL values

NOTE: This feature is turned off by default for performance reasons. You can turn it on per datatype and dbh, or via the module attribute hash (%Sybase::DBlib::Att and %Sybase::CTlib::Att).

The Sybase::CTlib and Sybase::DBlib modules include special features to handle DATETIME, MONEY, and NUMERIC/DECIMAL (CTlib only) values in their native formats correctly. What this means is that when you retrieve a date using ct_fetch() or dbnextrow() it is not converted to a string, but kept in the internal format used by the Sybase libraries. You can then manipulate this date as you see fit, and in particular 'crack' the date into its components.

The same is true for MONEY (and for CTlib NUMERIC values), which otherwise are converted to floating point values, and hence are subject to loss of precision in certain situations. Here they are stored as MONEY values, and by using operator overloading we can give you intuitive access to the cs_calc()/dbmnyxxx() routines.

This feature has been implemented by creating new classes in both Sybase::DBlib and Sybase::CTlib: Sybase::DBlib::DateTime, Sybase::DBlib::Money, Sybase::CTlib::DateTime, Sybase::CTlib::Money and Sybase::CTlib::Numeric (hereafter referred to as DateTime, Money and Numeric). All the examples below use the CTlib module. The syntax is identical for the DBlib module, except that the Numeric class does not exist.

To create data items of these types you call:

   $dbh = new Sybase::CTlib user, password;
   ...  # code deleted
   # Create a new DateTime object, and initialize to Jan 1, 1995:
   $date = $dbh->newdate('Jan 1 1995');

   # Create a new Money object
   $mny = $dbh->newmoney;       # Default value is 0

   # Create a new Numeric object
   $num = $dbh->newnumeric(11.111);

The DateTime class defines the following methods:


Convert to string (calls cs_convert()/dbconvert()).

@arr = $date->crack

'Crack' the date into its components.


Compare $date with $date2.

$date2 = $date->calc($days, $msecs)

Add or substract $days and $msecs from $date, and returns the new date.

NOTE: The minimal interval that Sybase understands is 1/300th of second, so amounts of less than 3 $msecs will NOT be visible.

($days, $msecs) = $date->diff($date2)

Compute the difference, in $days and $msecs between $date and $date2.

$time = $date->mktime
$time = $date->timelocal
$time = $date->timegm

Converts a Sybase DATETIME value to a Unix time_t value. The mktime and timelocal methods assumes the date is stored in local time, timegm assumes GMT. The mktime method uses the POSIX module (note that unavailability of the POSIX module is not a fatal error).

Both the str and the cmp methods will be called transparently when they are needed, so that

    print "$date"

will print the date string correctly, and

    $date1 cmp $date2

will do a comparison of the two dates, not the two strings.

crack executes cs_dt_crack()/dbdatecrack() on the date value, and returns the following list:

    ($year, $month, $month_day, $year_day, $week_day, $hour,
        $minute, $second, $millisecond, $time_zone) = $date->crack;

Compare this with the value returned by the standard Perl function localtime():

    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =

In addition, the values returned for the week_day can change depending on the locale that has been set.

Please see the discussion on cs_dt_crack() or dbdatecrack() in the Open Client / Open Server Common Libraries Reference Manual, chap. 2.

The Money and Numeric classes define these methods:


Convert to string (calls cs_convert()/dbconvert()).


Convert to a floating point number (calls cs_convert()/dbconvert()).


Compare two Money or Numeric values.


Set the value of $mny to $number.

$mny->calc($mny2, $op)

Perform the calculation specified by $op on $mny and $mny2. $op is one of '+', '-', '*' or '/'.

As with the DateTime class, the str and cmp methods will be called automatically for you when required. In addition, you can perform normal arithmetic on Money or Numeric datatypes without calling the calc method explicitly.

CAVEAT! You must call the set method to assign a value to a Money/Numeric data item. If you use

      $mny = 4.05

then $mny will lose its special Money or Numeric behavior and become a normal Perl data item.

When a new Numeric data item is created, the SCALE and PRECISION values are determined by the initialization. If the data item is created as part of a SELECT statement, then the SCALE and PRECISION values will be those of the retrieved item. If the item is created via the newnumeric method (either explicitly or implicitly) the SCALE and PRECISION are deduced from the initializing value. For example, $num = $dbh->newnumeric(11.111) will produce an item with a SCALE of 3 and a PRECISION of 5. This is totally transparent to the user.


The Sybase::DBlib 2PC calls have not been well tested.

There is a (approximately) 300 byte memory leak in the newdbh() function in Sybase/DBlib.xs. This function is called when a new connection is created. I have not been able to locate the real cause of the leak so far. Patches that appear to solve the problem are welcome!

I have a simple bug tracking system at . You can use it to check for known bugs, or to submit new ones.

You can also look for new versions/patches for sybperl in


Larry Wall - for Perl :-)

Tim Bunce & Andreas Koenig - for all the work on MakeMaker


Michael Peppler <>

Jeffrey Wong for the Sybase::DBlib DBMONEY routines.

W. Phillip Moore <> for the nsql() method.

Numerous folks have contributed ideas and bug fixes for which they have my undying thanks :-)

The sybperl mailing list <> is the best place to ask questions.

3 POD Errors

The following errors were encountered while parsing the POD:

Around line 1640:

Non-ASCII character seen before =encoding in 'voilà!'. Assuming CP1252

Around line 1646:

'=item' outside of any '=over'

Around line 1698:

You forgot a '=back' before '=head1'