Sybase: Find the name of the current database

If you need to switch to a given database, you can use the following statement:

1> use master
2> go

Replacing master by the database name you want to switch to.

If you want to figure out what’s the current database, there is unfortunately no @@db, @@dbid or @@dbname global variable. But you can check it over the current process ID:

1> select d.name from master..sysdatabases d, master..sysprocesses p where d.dbid=p.dbid and p.spid=@@spid
2> go
 name
 ------------------------------
 master

(1 row affected)

Update: As Peter correctly noticed, there are built-in functions you can use for this too:

1> select db_id()
2> go

 ------
      1

(1 row affected)
1> select db_name()
2> go

 ------------------------------
 master

(1 row affected)
1> select user_id()
2> go

 -----------
           1

(1 row affected)
1> select user_name()
2> go

 ------------------------------
 dbo

(1 row affected)
1> select suser_id()
2> go

 -----------
           1

(1 row affected)
1> select suser_name()
2> go

 ------------------------------
 sa

(1 row affected)

2 thoughts on “Sybase: Find the name of the current database

  1. You can also do it this shorter way:

    Displaying result for:
    ———————
    select db_name()

    ——————————
    master

    1 Row(s) affected

    1. And since you’ve prepared a nice list of those functions, just a last one to the list is “suser_name()”:

      Displaying result for:
      ———————
      select suser_name=suser_name(), user_name=user_name()

      suser_name user_name
      —————————— ——————————
      sa dbo

      1 Row(s) affected

      Regards!

Leave a Reply

Your email address will not be published. Required fields are marked *