views:

74

answers:

5

Hi guys,

I'm trying to write a MySQL script that creates several tables. I have:

CREATE TABLE `DataBase1`.`tbl_this`(
...
);
CREATE TABLE `DataBase1`.`tbl_that`(
...
);
... (14 more) ...

BUT, only the first CREATE TABLE statement is executed. I get no syntax errors. Erm, am I missing the MSSQL equivalent of GO ? What am I doing wrong here; how do I get this baby to run all the tables?

A: 

try this:

use database_name;

create table a..; create table b..; create table c..;

CrazyJoe
Worse. No tables were created at all.
rlb.usa
A: 

Are the tables referencing (e.g. primary keys and the like) one another? Tables are created serially, so if your second table is referencing a table that is not yet created, it will fail.

Matthew Jones
+3  A: 

The create table syntax looks fine. Probably the tool you use to execute your SQL just executes the first statement.

Florian Gutmann
+4  A: 

How are you executing this script?

If you are trying to run it programmatically, you should know that the MySQL API only executes one statement at a time by default. You can't string them together with semicolons and expect it to run all the statements.

You can execute each CREATE TABLE statement individually in a loop, or else you can run a script by feeding it as input to the mysql command-line client.

It's not as easy as it would seem to write a general-purpose script runner class in your application, because the full script syntax include many corner cases.

See examples of the corner cases in my answer to Loading .sql files from within PHP.

Bill Karwin
This is exactly the problem, MySQL Query Browser only processes the first command. I will mark @Florian_Gutmann because he was first and could use the points (as compared to 48K... jeez! are you contesting with Skeet?), gotta hook in the new fish with rep. : )
rlb.usa
LOL! No problem, @Florian was indeed first. Yes, MySQL Query Browser's query interface is just like running a single statement from within application code, in that it runs one statement. Query Browser should also have a "Run SQL Script..." menu option you can use to execute multiple statements from a file.
Bill Karwin
Scripting interfaces to MySQL only execute one command at a time. This is a good thing: it lessens the automatable impact of SQL injections. Some environments have an interface to multiple statements, eg. at C API level using `MYSQL_OPTION_MULTI_STATEMENTS_ON` or in PHP with `mysqli_multi_query`.
bobince
A: 

How do you execute your script ? If you do it from command line it should be something like this:

mysql -u[username] -p[password] --database DataBase1 < scriptname.sql
a1ex07