Find out current database name (MSSQL)

30k Views Asked by At

If I want to know the server I can use: @@SERVERNAME

Is there an equivalent function for getting database/catalog name.

I know that we can set it in the script with USE statement but what if it wasnt set and I wanted to query within a sproc what db I was using.

4

There are 4 best solutions below

2
On BEST ANSWER

db_name() will give you the name of the current database.

0
On

With the MSSQL queries below, you can check the current database:

SELECT DB_NAME()
GO

master

In addition, if you don't specify a database on sqlcmd, "master" database is used by default.

2
On

This should do it:

SELECT DB_NAME() AS DataBaseName

Per SQL Authority

0
On

db_name() will get you the name of database that you using. you can see the result with: select db_name()