Sometimes, while writing a stored procedure or a function in Microsoft SQL Server, you might want to access the current database. Either for information purposes or for conditional, database-specific logic.

The solution to this is the system function DB_NAME()

SELECT DB_NAME()

This will return a result like this:

dbname

You can use this for database-specific logic:

IF DB_NAME() = 'Spies'
    PRINT 'You are in the spies database. Delete your info to cover your tracks!';
ELSE
    PRINT 'You are in some other database';

This will return something like this:

dbname_logic

TLDR

You can use the DB_NAME() function to find out which database you are currently using.

Happy hacking!