Home > DeveloperSection > Forums > How to check database exists or not in sqlserver
Ankit Singh

Total Post:341

Points:2389
Posted on    January-17-2016 11:22 PM

 Database SQL Server 
Ratings:


 1 Reply(s)
 306  View(s)
Rate this:
I want to check  database exists or not in sqlserver please help me.


aditya kumar Patel

Total Post:242

Points:1722
Posted on    January-17-2016 11:29 PM

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


Don't want to miss updates? Please click the below button!

Follow MindStick