Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Question about creating and use database with "if exists()" at a time

sql database create database

  • Please log in to reply
1 reply to this topic

#1 Ehsan0101

Ehsan0101

    CC Regular

  • Member
  • PipPipPip
  • 38 posts
  • Location:Dhaka, Bangladesh
  • Learning:C#, Visual Basic .NET

Posted 05 October 2012 - 01:55 AM

Hello,
I'm a student of Procramming C# and now I'm reading SQL.

First I loved to use this code to create and use database at a time:
--Create database
CREATE DATABASE Library
GO
--Use Database
USE Library
GO

after that, I learned "if exists()" and I applied this code:
--Create database
IF NOT EXISTS (SELECT * FROM sys.databases where name = 'Library')
CREATE DATABASE Library
ELSE
PRINT 'The Library database is alreary exists!!'
GO
--Use Database
USE Library
GO

But now I want to create and use within a batch like this code:
--Create AND Use database
IF NOT EXISTS (SELECT * FROM sys.databases where name = 'Library')
BEGIN
CREATE DATABASE Library
USE Library
END
ELSE
BEGIN
USE Library
END
GO

But here is a problem :(

How can I do this at a time, please Help me


--
Best regards
ehsan
  • 0

#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 05 October 2012 - 02:26 AM

That script should work just fine anytime you execute but i will make a little change to it :

--Create AND Use database
IF NOT EXISTS (SELECT * FROM sys.databases where name = 'Library')
BEGIN
        CREATE DATABASE Library
END

USE Library

GO

you are gonna use Library anyway so i think it should be out of the ifs,
if you ask how to use that in code, well, you just throw that to execute just like any query.

make sure you connect to the database with an account with database creation privileges and don't specify database in the connection string

was that the question ?
  • 0





Also tagged with one or more of these keywords: sql, database, create database

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download