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

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

336032 次浏览

来自微软的脚本:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'


IF (EXISTS (SELECT name
FROM master.dbo.databases
WHERE ('[' + name + ']' = @dbname
OR name = @dbname)))
IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
Do your thing...

顺便说一下,这直接来自SQL Server Studio,所以如果你有这个工具,我建议你开始使用各种可用的“Script xxxx AS”函数。会让你的生活更轻松!:)

实际上,最好使用:

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

请参阅https://learn.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql并注意,这对于Azure SQL数据库是没有意义的。

我喜欢@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

试试这个

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
  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;"