-1

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?

Aashray
  • 2,753
  • 16
  • 22
karthi
  • 1,059
  • 3
  • 10
  • 21
  • 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 Answers6

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

You can use show databases; SQL query.

Michal Borek
  • 4,584
  • 2
  • 30
  • 40
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]
0

You can use sp_databases command in sql server query window

Rohan
  • 3,068
  • 1
  • 20
  • 26