Checking if database exists or not in SQL Azure

前端 未结 3 1652
情书的邮戳
情书的邮戳 2021-01-15 01:24

Could any one please tell me how to code whether a database exists or not in sql azure ?

相关标签:
3条回答
  • 2021-01-15 01:58

    Have you tried querying the sys.databases table? That should give you what you're looking for. More info here.

    Note: You'll want to run this query against the Master database. Otherwise, you'll only see the name of the current database (and Master).

    0 讨论(0)
  • 2021-01-15 02:04

    Select count(*) from sysobjects where name = 'testdb' returns 0 if not found. put the name of your Database and we will edit the script for you .. all you need to do is copy and paste ok..? here are some additional things you could try as well

    Method 1: Use sys.sysdatabases view

    IF EXISTS(SELECT * FROM sys.sysdatabases where name=@testdb)
        PRINT 'The database exists' else PRINT 'The database does not exist'
    

    Method 2: Use sysdatabases system table from master database

    IF EXISTS(SELECT * FROM master..sysdatabases WHERE name=@testdb)
        PRINT 'The database exists' else print 'The database does not exist'
    

    Method 3: Using of sp_msforeachdb

    --If you dont get a message, the database doesn't exist
    DECLARE @sql varchar(1000)SET @sql='if ''?''='''+@ testdb+''' print ''the database exists'''EXEC sp_msforeachdb @sql 
    

    Method 4: Using sp_msforeachdb with information_schema.schemata

    --If you dont get a message, the database doesn't exist
    DECLARE @sql varchar(1000)
    SET @sql='if exists(select * from ?.information_schema.schemata wherecatalog_name='''+@ testdb+''') print ''the database exists'''
    EXEC sp_msforeachdb @sql
    
    0 讨论(0)
  • 2021-01-15 02:08
    if exists (select * from master.sys.databases where name = '[enter name here]')
    
    0 讨论(0)
提交回复
热议问题