使用 VB.NET 检查 MSSQL 中是否存在数据库的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30475227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:09:09  来源:igfitidea点击:

What's the simplest way to check if database exists in MSSQL using VB.NET?

sqlsql-serverdatabasevb.net

提问by Nyawk Nyawk

I'm trying to check if a database exists in the Microsoft SQL Server, what's the simplest way to do that? I just want it to return a true or false value then I would create a database if it doesn't exist. Any help would be appreciated, thanks.

我正在尝试检查 Microsoft SQL Server 中是否存在数据库,最简单的方法是什么?我只希望它返回一个 true 或 false 值,如果它不存在,我会创建一个数据库。任何帮助将不胜感激,谢谢。

回答by CeOnSql

Connect to a system-db (master, msdb, tempdb or model) - because you can be sure that they exist! Then you can select the list of database like this:

连接到系统数据库(master、msdb、tempdb 或模型) - 因为您可以确定它们存在!然后你可以像这样选择数据库列表:

select * from sys.databases 

or if you want to know if a specific db exists:

或者如果您想知道特定数据库是否存在:

select * from sys.databases where name = 'NameOfYourDb'

If you connect without a database name in your connection string (belongs to which provider you are using) you should automatically be connect to your default database (which is "master" by default)

如果您的连接字符串中没有数据库名称(属于您使用的提供程序),您应该自动连接到您的默认数据库(默认情况下为“master”)

回答by Indra Prakash Tiwari

Try below one

试试下面一个

Declare @Dbname varchar(100)

SET @Dbname = 'MASTER'

if exists(select * from sys.databases where name = @Dbname)
select 'true'
else 
select 'false'

this is specially for SQL Server

这是专为 SQL Server 设计的

回答by F0r3v3r-A-N00b

You can try the following query :

您可以尝试以下查询:

select * from sys.databases where [name] = <name of database>