how to check does some database exist ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • adam

    how to check does some database exist ?

    hello

    What query shoul I send to SQL serwer ( in transact SQL language ) to check
    does some database exist on serwer ? It similar to problem "does some table
    exist in database" - resolve to it is query:

    use db_silnik
    IF EXISTS (SELECT * FROM prad)
    PRINT 'table exist'

    but what is the query to check does some database exist on serwer ?

    best regards
    Adam

  • Simon Hayes

    #2
    Re: how to check does some database exist ?

    There are (at least) a couple of ways:

    select db_id('SomeData base') -- if NULL, the database doesn't exist

    if not exists (
    select *
    from master.dbo.sysd atabases
    where name = 'SomeDatabase')
    print 'Database does not exist'


    Note that these queries won't tell you if the database is accessible or
    not - it may be offline or loading, or your login may not have been
    granted access to it; see DATABASEPROPERT YEX() and HAS_DBACCESS() in
    Books Online.

    Simon

    Comment

    • Erland Sommarskog

      #3
      Re: how to check does some database exist ?

      adam (ereuseen@wp.pl ) writes:[color=blue]
      > What query shoul I send to SQL serwer ( in transact SQL language ) to
      > check does some database exist on serwer ?[/color]

      IF db_name(@db) IS NOT NULL
      PRINT 'Database exists'
      [color=blue]
      > It similar to problem "does some table exist in database" - resolve to
      > it is query:
      >
      > use db_silnik
      > IF EXISTS (SELECT * FROM prad)
      > PRINT 'table exist'[/color]

      Ehum, this query will fail if the table does not exist. This query checks
      whether there is any data in the table.

      To check whether a table exists, use:

      IF object_id(@tbl, 'U') IS NOT NULL
      PRINT 'Table exists'



      --
      Erland Sommarskog, SQL Server MVP, esquel@sommarsk og.se

      Books Online for
      SQL Server SP3 at
      Get the flexibility you need to use integrated solutions, apps, and innovations in technology with your data, wherever it lives—in the cloud, on-premises, or at the edge.

      Comment

      Working...