7

I want to add a new column 'IPkey' in CDRLive, which is the primary key 'pkey' in ACIPin. pkey is bigint, not null.

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

Failed. The error:

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.
John Woo
  • 258,903
  • 69
  • 498
  • 492

1 Answers1

18

If you want the column to have a NOT NULL constraint you need to do it in the following order.

  1. ALTER TABLE CDRLive ADD IPkey bigint NULL go
  2. Fill up the column with the data you prefer.
  3. ALTER TABLE CDRLive ADD IPkey bigint NOT NULL go
  4. ALTER TABLE CDRLive ADD CONSTRAINT CDRLive_IPkey FOREIGN KEY(IPkey) REFERENCES ACIPin(pkey)
Eli Ekstein
  • 466
  • 8
  • 19
  • Step 2, the data can be filled from ACIPin using where clause. I just want to make sure your order is correct. –  Mar 08 '13 at 16:29
  • @Love Yeah, you need to figure out a way based on your data to assign the right foreign key to `CDRLive`. Or if you don't care for the old data, you can do as graceemile said to insert a 0 in all old rows and create the foreign key with the `WITH NOCHECK` clause. – Eli Ekstein Mar 08 '13 at 16:38
  • Just in case: Remember "GO" is a non-SQL-native batch terminator, which can be modified, as said in [this answer](http://stackoverflow.com/a/2299280/1764416) – FranciscoBouza Feb 09 '15 at 13:34