I want to check whether the database name is alredy exists in sql server 2008 or not. If it's not means i need to create the database. How can i check this?
Asked
Active
Viewed 2,285 times
-1
-
for example i want to check if the database `example`is already existed or not. if it's not means i need to create `example` database. – karthi May 07 '13 at 12:18
6 Answers
2
Connection connection = DriverManager.getConnection();
ResultSet resultSet = connection.getMetaData().getCatalogs();
while (resultSet.next()) {
// Get the database name
String databaseName = resultSet.getString(1);
}
resultSet.close();
0
If you are doing it in a startup query, combine the two actions using create if not exists
SQL statement (see your DBMS actual documentation for the exact syntax).

Stefano Sanfilippo
- 32,265
- 7
- 79
- 80
0
Possible this be helpful for you -
CREATE FUNCTION dbo.is_db_exists
(
@db_name NVARCHAR(100)
)
RETURNS INT
AS BEGIN
IF EXISTS (
SELECT 1
FROM sys.databases
WHERE name = @db_name
) RETURN 1
RETURN 0
END
Or this this query -
IF DB_ID('<db_name>') IS NOT NULL
PRINT 'DB is exists'

Devart
- 119,203
- 23
- 166
- 186
0
You can check if it NOT EXISTS:
IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'YourDBName')
CREATE DATABASE [YourDBName]
Or you can check if it EXISTS then drop it:
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'YourDBName')
DROP DATABASE [YourDBName]

A. Cristian Nogueira
- 725
- 1
- 8
- 25