添加新列并设置外键关系

时间:2013-03-08 15:51:40

标签: sql-server tsql

我想在CDRLive中添加一个新列'IPkey',它是ACIPin中的主键'pkey'。 pkey是bigint,而不是null。

ALTER TABLE CDRLive ADD IPkey bigint NOT NULL
go
ALTER TABLE CDRLive
ADD CONSTRAINT CDRLive_IPkey FOREIGN KEY(IPkey) REFERENCES ACIPin(pkey) 

失败。错误:

Msg 4901, Level 16, State 1, Line 2
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT     definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'IPkey' cannot be added to non-empty table 'CDRLive' because it does not satisfy these conditions.
 Msg 1769, Level 16, State 1, Line 1

 Foreign key 'CDRLive_IPkey' references invalid column 'IPkey' in referencing table 'CDRLive'.
 Msg 1750, Level 16, State 0, Line 1
 Could not create constraint. See previous errors.

1 个答案:

答案 0 :(得分:15)

如果您希望列具有NOT NULL约束,则需要按以下顺序执行此操作。

  1. ALTER TABLE CDRLive ADD IPkey bigint NULL go
  2. 使用您喜欢的数据填写列。
  3. ALTER TABLE CDRLive ADD IPkey bigint NOT NULL go
  4. ALTER TABLE CDRLive ADD CONSTRAINT CDRLive_IPkey FOREIGN KEY(IPkey) REFERENCES ACIPin(pkey)
相关问题