如何检查SQL Server中是否存在数据库?

时间:2009-03-24 19:56:11

标签: sql-server database tsql

使用TSQL检查SQL Server上是否存在数据库的理想方法是什么?似乎有多种方法可以实现这一点。

7 个答案:

答案 0 :(得分:473)

实际上最好使用:

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

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

答案 1 :(得分:143)

来自微软的脚本:

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'

答案 2 :(得分:33)

IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
  Do your thing...

顺便说一句,这直接来自SQL Server Studio,因此如果您可以访问此工具,我建议您开始使用可用的各种“Script xxxx AS”功能。会让你的生活更轻松! :)

答案 3 :(得分:5)

我喜欢@ Eduardo的答案,我喜欢接受的答案。我喜欢从这样的东西中取回一个布尔值,所以我为你们写了一遍。

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

现在您可以像这样使用它:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

答案 4 :(得分:0)

尝试

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

答案 5 :(得分:0)

另一种方法是将SqlDataReaderSqlConnectionSqlCommand一起使用。使用HasRows属性。如果数据库存在,则为true,如果数据库不存在,则为false

示例(在此示例中,数据库名称为“匹配”):

    string CreateDatabaseConnectionString="/*the connection string*/";

    public static bool DatabaseExists()
    {
        bool Count;
        string DatabaseCheckString = "select name from master.sys.databases where name='Matches'";
        SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
        SqlCommand DatabaseExistsCommand = new SqlCommand(DatabaseCheckString, MyConn);
        MyConn.Open();
        SqlDataReader Reader = DatabaseExistsCommand.ExecuteReader();
        Count = Reader.HasRows;
        MyConn.Close();
        return Count;
    }

答案 6 :(得分:0)

  Public Function SQLDatabaseExist(ByVal DefaultConnectionString As String, ByVal DataBaseName As String) As Boolean
Try
    'CREATE DATABASE
    Dim SqlString As String = ""
    SqlString = "SELECT CASE WHEN EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" & DataBaseName & "') THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END"
    Dim ExcRet As Integer = 0
    Using connection As New SqlConnection(DefaultConnectionString)
        Dim command As New SqlCommand(SqlString, connection)
        command.Connection.Open()
        ExcRet = command.ExecuteScalar()
        command.Connection.Close()
        command.Dispose()
    End Using
    Return ExcRet
Catch ex As Exception
    Return False
End Try

结束函数

''注意连接字符串中的初始目录必须是master! '示例默认连接字符串

Dim DefaultConnectionString As String = "Data Source=localhost\SQLSERVER2008;Initial Catalog=Master; User ID=SA; Password='123123'; MultipleActiveResultSets=false; Connect Timeout=15;Encrypt=False;Packet Size=4096;"