SQL - create database and tables in one script

Viewed 29001

Sorry if already asked, but I can't find anything on this.

I am moving something over from MySQL to SQL Server I want to have a .sql file create a database and tables within the database. After working out syntax kinks I have gotten the files to work (almost).

If I run

IF db_id('dbname') IS NULL 
    CREATE DATABASE dbname

it works fine, and if I run

CREATE TABLE dbname.dbo.TABLE1 (
);
...
CREATE TABLE dbname.dbo.TABLEN (
);

it also works fine. But, if I run them in the same file I get this error

Database 'dbname' does not exist

Right now, the CREATE TABLE statements are not within the IF statement, which I would like, but I also cannot seem to find the syntax for that. ( { } does not work?)

So my big question is, how do I ensure a particular command in a .sql file is completed before another in SQL Server?

My second question is, how do I include multiple instructions within an IF clause?

To be clear, I have been running this into sqlcmd.

4 Answers
Related