How to check if a database exists in SQL Server?

前端 未结 5 746
灰色年华
灰色年华 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: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
    

提交回复
热议问题