13

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.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
logixologist
  • 3,694
  • 4
  • 28
  • 46

4 Answers4

19

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

Paul Abbott
  • 7,065
  • 3
  • 27
  • 45
  • @logixologist: if this answer helped you solve your problem, then please [**accept this answer**](http://meta.stackoverflow.com/q/5234/153998). This will show your appreciation for the people who *spent their own time to help you*. – marc_s Sep 28 '16 at 05:04
  • I would have done it immediately but it has a timer set on it. – logixologist Sep 28 '16 at 13:31
7

This should do it:

SELECT DB_NAME() AS DataBaseName

Per SQL Authority

Michael Armes
  • 1,056
  • 2
  • 17
  • 31
5

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

Ali M
  • 801
  • 11
  • 23
3

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.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129