How to check if a database exists in SQL Server?

前端 未结 5 721
灰色年华
灰色年华 2020-11-27 11:55

What is the ideal way to check if a database exists on a SQL Server using TSQL? It seems multiple approaches to implement this.

相关标签:
5条回答
  • 2020-11-27 12:33

    From a Microsoft's script:

    DECLARE @dbname nvarchar(128)
    SET @dbname = N'Senna'
    
    IF (EXISTS (SELECT name 
    FROM master.dbo.sysdatabases 
    WHERE ('[' + name + ']' = @dbname 
    OR name = @dbname)))
    
    -- code mine :)
    PRINT 'db exists'
    
    0 讨论(0)
  • 2020-11-27 12:38
    IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
      Do your thing...
    

    By the way, this came directly from SQL Server Studio, so if you have access to this tool, I recommend you start playing with the various "Script xxxx AS" functions that are available. Will make your life easier! :)

    0 讨论(0)
  • 2020-11-27 12:38

    TRY THIS

    IF EXISTS 
       (
         SELECT name FROM master.dbo.sysdatabases 
        WHERE name = N'New_Database'
        )
    BEGIN
        SELECT 'Database Name already Exist' AS Message
    END
    ELSE
    BEGIN
        CREATE DATABASE [New_Database]
        SELECT 'New Database is Created'
    END
    
    0 讨论(0)
  • 2020-11-27 12:42

    I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

    CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
    RETURNS bit
    AS
    BEGIN
        declare @result bit = 0 
        SELECT @result = CAST(
            CASE WHEN db_id(@dbname) is not null THEN 1 
            ELSE 0 
            END 
        AS BIT)
        return @result
    END
    GO
    

    Now you can use it like this:

    select [dbo].[DatabaseExists]('master') --returns 1
    select [dbo].[DatabaseExists]('slave') --returns 0
    
    0 讨论(0)
  • 2020-11-27 12:48

    Actually it's best to use:

    IF DB_ID('dms') IS NOT NULL
       --code mine :)
       print 'db exists'
    

    See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql

    0 讨论(0)
提交回复
热议问题