Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2003
    Posts
    8

    Unanswered: Current Database name

    in T-SQL how do I check what is the current database name?
    In my script, I used:

    .
    .
    .
    OPEN DBList
    FETCH NEXT FROM DBList INTO @DB_name

    WHILE @@FETCH_STATUS = 0
    BEGIN
    SET @SQLString = N'USE ' + @DB_name
    EXEC (@SQLString)
    .
    .
    .
    Somehow it always stayed "Master" DB and never on go to the next.

    Thanks

  2. #2
    Join Date
    Dec 2002
    Location
    Czech Republic
    Posts
    249
    A1. select db_name()
    A2. Dynamic exec runs in separate query/security context, subcontext of current query. If you want to run some code in different database context and you select variable database name, you must put this code together with USE into dynamic code.

  3. #3
    Join Date
    Oct 2002
    Posts
    369

    Re: Current Database name

    Q1 in T-SQL how do I check what is the current database name?
    A3 It is not clear what the purpose of the script is. If what is needed is a list of DBs consider using sp_Databases or the Information_Schema.Schemata view, for example:

    Exec sp_Databases

    Select Catalog_Name From Information_Schema.Schemata

    A4 There are several ways to "check what is the current database name", consider Db_Name(), (as Ispaleny already suggested, which is also the simplest), or the Information_Schema views, for example:

    Use Pubs
    Go

    Select
    Top 1 Table_Catalog As 'The Current DB Name using the Information_Schema views is:'
    From
    Information_Schema.Tables

    Select Db_Name() As 'The Current DB Name using Db_Name() is:'

    Use Tempdb
    Go

    Select
    Top 1 Table_Catalog As 'The Current DB Name using the Information_Schema views is:'
    From
    Information_Schema.Tables

    Select Db_Name() As 'The Current DB Name using Db_Name() is:'
    Last edited by DBA; 01-17-03 at 23:37.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •