Get name of current database

,

Retrieve the name of the current database for use with bcp and other procedures that require database name. 

This will help increase the portability of code and less maintenance required when migrating code to new database/server.

CREATE PROCEDURE dbo.spGetDatabaseName

/*
  * This will return the current database name for use 
      with bcp utility and other functions that require 
      database name.
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  * This requires that the user running the procedure has 
      at least read-only access to master..sysdatabase and
      the current database..sysfiles tables.
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
@DbName VARCHAR(50) = NULL OUTPUT

AS

SET @DbName = 
  (SELECT SD.[name]
    FROM sysfiles SF 
      INNER JOIN master..sysdatabases SD 
        ON SF.[filename] = SD.[filename]
     -- COLLATE Latin1_General_CS_AS)

/*
 COLLATE being provided in case of SQL 2K server database
  having different collation than server default
*/

Rate

5 (1)

Share

Share

Rate

5 (1)