Are you on the correct server and the correct database with MSSQL

  • It's very important to make sure that you are using the right server and the right database.
  • Nothing worth that deleting data on a production server.
  • Nothing worth than inserting test data in a production database.

Applies to:

  • Microsoft SQL Server 2000
  • Microsoft SQL Server 2005

Server and database name

  1. SELECT CAST(@@SERVERNAME AS VARCHAR(20)) AS 'Server',
  2.        CAST(DB_NAME() AS VARCHAR(20)) AS 'Database'
  3. go
Server               Database
-------------------- --------------------
W2K3BASE             master

(1 row(s) affected)
  • @@servername: returns a 128 long nvarchar string, name of the server. I truncated it with the cast to make it readable on the screen. You can change the server name with sp_addserver and by restarting the Microsoft SQL Server.
  • db_name(): returns a 128 long nvarchar string, name of the server. I truncated it with the cast to make it readable on the screen.

Checking if you are on the correct server and the correct database

  1. IF @@SERVERNAME = 'W2K3BASE'
  2. BEGIN
  3.     PRINT 'Server: W2K3BASE'
  4. END;
  5.  
  6. IF DB_NAME() = 'master'
  7. BEGIN
  8.     PRINT 'db: Master'
  9. END;
  10.  
  11. IF DB_NAME() <> 'sql911'
  12. BEGIN
  13.     PRINT 'Wrong database, currently in: ' + DB_NAME()
  14. END;
  15. go
Server: W2K3BASE
db: Master
Wrong database, currently in: master