SQL - 在一个脚本中创建数据库和表 [英] SQL - create database and tables in one script

查看:429
本文介绍了SQL - 在一个脚本中创建数据库和表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果已经提出,但我找不到任何东西。

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

我从MySQL移动到SQL Server我想有一个.sql文件在数据库内创建数据库和表。

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 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

现在,CREATE TABLE语句不在IF语句中,我想,但我似乎找不到的语法。 ({}不起作用?)

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?)

所以我的大问题是,如何确保.sql文件中的特定命令在SQL中另一个命令之前完成服务器?

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

我的第二个问题是,如何在IF子句中包含多条指令?

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


推荐答案

放置 GO 命令。

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

GO

CREATE TABLE dbname.dbo.TABLE1 ( 
); 

CREATE TABLE dbname.dbo.TABLEN ( 
); 

至于将表语句放在IF中,您将无法执行命令。

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.

块if的语法如下:

IF condition
BEGIN
   ....
   ....
END

这篇关于SQL - 在一个脚本中创建数据库和表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆