简体   繁体   English

SQL-运行多个ALTER查询

[英]SQL - Running multiple ALTER queries

i'm having trouble with running multiple ALTER commands in a single query. 我在单个查询中运行多个ALTER命令时遇到麻烦。

Whenever im trying to run the following code : 每当我尝试运行以下代码时:

ALTER TABLE Book$
ALTER COLUMN PID INT NOT NULL

ALTER TABLE Book$
ADD CONSTRAINT pk_book PRIMARY KEY(PID)

I get an error : 我得到一个错误:

Cannot define PRIMARY KEY constraint on nullable column in table 'Book$'.

But if i run the queries separately , first : 但是,如果我分别运行查询,首先:

ALTER TABLE Book$
ALTER COLUMN PID INT NOT NULL

And then : 接着 :

ALTER TABLE Book$
ADD CONSTRAINT pk_book PRIMARY KEY(PID)

Everything seems to work just fine. 一切似乎都正常。 What am i doing wrong? 我究竟做错了什么? Thanks! 谢谢!

Add GO (batch separator) in between to fix the problem 在两者之间添加GO (批处理分隔符)以解决问题

ALTER TABLE Book$
ALTER COLUMN PID INT NOT NULL

GO

ALTER TABLE Book$
ADD CONSTRAINT pk_book PRIMARY KEY(PID)

Without GO the entire script will be considered as single script 如果没有GO则整个脚本将被视为单个脚本

I'm not sure which database you are using. 我不确定您使用的是哪个数据库。 To explain what is happening, though, you need to understand two phases of statement processing: Compilation and Execution. 但是,要说明正在发生的情况,您需要了解语句处理的两个阶段:编译和执行。

The Compilation phase reads the statement and defines the execution plan. 编译阶段读取语句并定义执行计划。 The Execution phase then runs the plan. 然后执行阶段将运行计划。 Nothing about the table changes just because a statement is compiled. 该表没有任何变化,只是因为已编译一条语句。

What is happening is that the two statements are compiled and then executed. 发生的事情是两个语句被编译然后执行。 When the second is compiled, nothing has changed (well, except for the fact that the first statement's execution plan is stored somewhere). 编译第二条语句后,什么都没有改变(好,除了第一条语句的执行计划存储在某个地方)。 Hence, you are getting a compilation error. 因此,您遇到编译错误。

When you run the two separately, the changes from the first take place and then the second does not generate an error. 当您分别运行两者时,从第一个进行的更改然后在第二个进行的更改不会产生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM