HOW TO CHECK DATABASE EXISTS OR NOT IN SQLSERVER

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
 697  View(s)
Ratings:
Rate this:
I want to check  database exists or not in sqlserver please help me.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to Check If Database Exists In SQL Server

    if we want to check database exists or not  we can know  four way.

    -- Solution number (1)
    DECLARE @Database_Name varchar(100)
    SET @Database_Name='forum'
    IF EXISTS(SELECT * FROM sys.sysdatabases where name=@Database_Name)
    PRINT 'The database already exists'
    else
    PRINT 'The database does not exist'


    -- Solution number (2)
    DECLARE @Database_Name varchar(100)
    SET @Database_Name='forum'
    IF EXISTS(SELECT * FROM master..sysdatabases WHERE name=@Database_Name)
    PRINT 'The database already exists'
    else
    print 'The database does not exist'


    -- Solution number (3)
    DECLARE @Database_Name varchar(100)
    SET @Database_Name='forum'
    DECLARE @sql varchar(1000)
    SET @sql='if ''?''='''+@Database_Name+''' print ''the database already alexists'''
    EXEC sp_msforeachdb @sql


    -- Solution number (4)
    DECLARE @Database_Name varchar(100)
    SET @Database_Name='forum'
    DECLARE @sql varchar(1000)
    SET @sql='if exists(select * from ?.information_schema.schemata where
    catalog_name='''+@Database_Name+''') print ''the database already exists'''
    EXEC sp_msforeachdb @sql

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!