sql-server - 添加新列并设置外键关系

标签 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.

最佳答案

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

  1. ALTER TABLE CDRLive ADD IPkey bigint NULL 去
  2. 在该列中填写您喜欢的数据。
  3. ALTER TABLE CDRLive ADD IPkey bigint NOT NULL 去
  4. 更改表 CDRLive 添加约束 CDRLive_IPkey 外键(IPkey)引用 ACIPin(pkey)

关于sql-server - 添加新列并设置外键关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297947/

相关文章:

sql - 在不删除表/列的情况下将现有列更改为计算和持久化

sql - 在更新语句上使用输出子句时出现奇怪的错误?

SQL 桶确定年龄分组

sql-server - 如何列出 SSRS 数据集中动态 SQL 查询的字段

mysql - 用于根据特定条件计算记录并返回计数的 SQL 脚本

sql - 创建类似于 SQL Server 2005/2008 中当前表的临时表

sql - 获取具有十进制值的数字

sql-server - 在 SQL Server 2008 R2 中开始调试时发生错误,错误 HRESULT E_FAIL 已从对 COM 组件的调用返回。 (mscorlib)

c# - 使用 SignalR 推送通知

sql - 为什么在ssrs中使用sql语言而不使用mdx语言?