2

我创建了我的数据库的脚本。

但是当我运行它时,脚本不会创建数据库。它跳过“创建数据库”语句,只创建表(在我目前选择的数据库上,所以不理想....)

(顺便说一句,查询执行没有错误。)

为什么会这样?为什么不能一次性创建数据库并编辑其中的内容?

(我知道你可以先检查数据库是否存在,但这不应该从一开始就发生)

--我的脚本--

CREATE DATABASE [EthicsDB] 

USE [EthicsDB]
go

CREATE TABLE [dbo].[TempEmployee](
    [PersonnelNumber] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](80) NULL,
    [SurName] [varchar](80) NULL,
    [ManagerEmail] [varchar](80) NULL,
    [ManagerName] [varchar](80) NULL,
 CONSTRAINT [PK_TempEmployee] PRIMARY KEY CLUSTERED 
(
    [PersonnelNumber] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
4

4 回答 4

5

You must use GO after CREATE DATABASE [EthicsDB].

于 2013-06-27T09:10:39.107 回答
2

If you run the SQL as provided you get an error message on the line

USE [EthicsDB]

This occurs as when SQL Servers runs SQL commands via SQL CMD it process the SQL in batches.

As you have no GO statement after the Create database statement it maybe that SQL Server does not yet recognise that a new database Ethics has been created and thus when you attempt to use the database via USE [EthicsDB] the statement fails.

As your SQL Statements are not wrapped in a transaction and as you are not checking for errors then if SQL Server encounters an error it will raise the error but also continue to process the rest of the query.

In the query provided this leads to the new tables being created in the current database.

To correct the problem modify your query to

CREATE DATABASE [EthicsDB] 
go
USE [EthicsDB]
go
于 2013-06-27T09:21:50.690 回答
2

试试这个——

USE [master]
GO

IF  EXISTS (
    SELECT 1 FROM sys.databases WHERE name = N'EthicsDB'
)
DROP DATABASE [EthicsDB]
GO

CREATE DATABASE [EthicsDB]
GO --<----

USE [EthicsDB]
GO

CREATE TABLE [dbo].[TempEmployee](
    [PersonnelNumber] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](80) NULL,
    [SurName] [varchar](80) NULL,
    [ManagerEmail] [varchar](80) NULL,
    [ManagerName] [varchar](80) NULL,
 CONSTRAINT [PK_TempEmployee] PRIMARY KEY CLUSTERED 
(
    [PersonnelNumber] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
于 2013-06-27T09:10:03.947 回答
0

您可能应该将每个操作包装在事务块中。

此外,当您创建表时,我通常会先检查它是否已经存在。

如果运行创建数据库,会发生什么?

于 2013-06-27T09:08:49.560 回答