SQL - 在一个脚本中创建数据库和表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3373268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL - create database and tables in one script
提问by sas4740
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).
我正在将某些东西从 MySQL 转移到 SQL Server 我想要一个 .sql 文件在数据库中创建一个数据库和表。在解决了语法问题之后,我已经让文件开始工作了(几乎)。
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?)
现在,CREATE TABLE 语句不在我想要的 IF 语句中,但我似乎也找不到它的语法。( { } 不起作用?)
So my big question is, how do I ensure a particular command in a .sql file is completed before another in SQL Server?
所以我的大问题是,如何确保 .sql 文件中的特定命令在 SQL Server 中的另一个命令之前完成?
My second question is, how do I include multiple instructions within an IF clause?
我的第二个问题是,如何在 IF 子句中包含多个指令?
To be clear, I have been running this into sqlcmd.
需要明确的是,我一直在将它运行到 sqlcmd 中。
回答by Fosco
Put a GO
command between queries.
GO
在查询之间放置一个命令。
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.
至于将表语句放在 IF 中,由于 GO 命令,您将无法这样做。之后您可以创建额外的 IF 语句,以检查每个表是否预先存在。
The syntax for a block if is:
块 if 的语法是:
IF condition
BEGIN
....
....
END
回答by Jeffrey L Whitledge
Between creating the database and creating the tables you will need a USE statement.
在创建数据库和创建表之间,您将需要一个 USE 语句。
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.
此外,就像其他人所说的那样,GO 和 BEGIN...END。
回答by David Espart
回答by Mitch Wheat
By placing a GO
between statements (to create separate batches of statements)
通过GO
在语句之间放置一个(以创建单独的语句批次)