How to check for the existence of a DB?

前端 未结 8 2215
Happy的楠姐
Happy的楠姐 2020-12-18 05:52

I am wondering if there is an elegant way to check for the existence of a DB? In brief, how do test the connection of a db connection string?

Thanks

8条回答
  •  情话喂你
    2020-12-18 06:50

    try

    IF NOT EXISTS(SELECT * FROM sys.databases WHERE [name] = @name)
       CREATE DATABASE @name;
    GO
    

    or

    IF db_id(@name) IS NOT NULL
       CREATE DATABASE @name;
    GO
    

    or SqlConnection.ChangeDatabase(String). I think it could use less sql server resources then new connection attempt.

提交回复
热议问题