17

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.

1
  • 3
    These statements aren't being executed in parallel, so you might want to revise your title. Commented Jul 30, 2010 at 16:09

4 Answers 4

24

Put a GO command between queries.

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

GO

CREATE TABLE dbname.dbo.TABLE1 ( 
); 

CREATE TABLE dbname.dbo.TABLEN ( 
); 

As for putting the table statements in the IF, you wouldn't be able to because of the GO command. You could create additional IF statements afterwards, to check for each tables pre-existence.

The syntax for a block if is:

IF condition
BEGIN
   ....
   ....
END
Sign up to request clarification or add additional context in comments.

1 Comment

while simple, this isn't always an option, see docs: "GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor." learn.microsoft.com/en-us/sql/t-sql/language-elements/…
8

Between creating the database and creating the tables you will need a USE statement.

USE dbname

This way the tables will be created in the correct place, without having to specify the DB name on everything.

Also, GO and BEGIN...END like everyone else is saying.

Comments

2

You have to separate the statements with the GO keyword:

sql query
GO

another sql query
GO

and so on

Comments

1

By placing a GO between statements (to create separate batches of statements)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.