Article

How to determine the current database context in SQL Server

I like to run a check script I’ve crafted that tells me stats on the database before I upgrade and perform schema changes.  To make the script more universal, I wanted it to report the name of the database the stats are for (for printing purposes). I knew how to check the database server hostname (IF @@SERVERNAME = ‘[expected hostname]’ … ) but I couldn’t find how to check the database context on that server. 

I found my answer: db_name()

Now I can check server name and database context before running code changes:

IF db_name() != N'[database]’ BEGIN …

Comments Closed.