1

I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:

IF (db_id('db') is null) BEGIN
    print 'Must create the database!';
    CREATE DATABASE db;
END

USE db;

IF (object_id('test_table', 'U') is null) BEGIN
    print 'Must create the table!';
    CREATE TABLE test_table (
        id int
    );
END

I'm getting a strange error with this:

Database 'db' does not exist. Make sure that the name is entered correctly.

I'm guessing that it's parsing the script before running it and finding that 'db' doesn't exist, so it can't use it.

There must be a solution to this. Any help is appreciated.

SOLVED!

I realised 5 minutes after posting that the GO keyword solves the problem. Here is the fixed code:

IF (db_id('db') is null) BEGIN
    print 'Must create the database!'
    CREATE DATABASE db;
END

GO
USE db

IF (object_id('test_table', 'U') is null) BEGIN
    print 'Must create the table!';
    CREATE TABLE test_table (
        id int
    );
END

Sorry for wasting everyone's time.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Mr_Bean
  • 139
  • 1
  • 15

3 Answers3

2

SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.

If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT for SQL Server and MySQL, respectively.

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
1

Something along the lines of Check if table exists in SQL Server would probably work (With a slight change)

IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END
Community
  • 1
  • 1
jama
  • 325
  • 1
  • 6
0

I might suggest using the built-in SQL syntax -

CREATE DATABASE name IF NOT EXISTS;

And subsequently

CREATE TABLE name(definition) IF NOT EXISTS;

DigitalJedi805
  • 1,486
  • 4
  • 16
  • 41