添加引用查找的列

时间:2017-09-21 16:26:04

标签: sql-server ddl

在SQL Server中,我有一个主表,我想要添加一列。该列将包含一个引用另一个表的ID字段的int,一个查找:

Statuses
ID    Status
0     ''
1     'Destroyed'
2     'Reassigned'

我想将一个列(StatusID)添加到MainTable,输入int,它只能保存Statuses.ID中找到的值。

Statuses.ID是主键(当然)。

我希望无法删除MainTable中引用的状态中的行。

我尝试了各种搜索,但是有太多细节无法生成良好的搜索结果。

------------------------

结果(太平洋时间09/21/17,1306):

USE TIL
GO

ALTER TABLE TACI
    ADD StatusID INT;

(执行)

USE TIL
GO

ALTER TABLE dbo.TACI
ADD CONSTRAINT FK_STATUS
    FOREIGN KEY (ID)
    REFERENCES dbo.Statuses (ID);

`Msg 547,Level 16,State 0,Line 2 ALTER TABLE语句与FOREIGN KEY约束冲突" FK_STATUS"。冲突发生在数据库" TIL",表" dbo.Statuses",列' ID' .``

很高兴知道冲突是什么......

Statuses.ID(PK, int, not null)

TACI.StatusID(int not null)。我创造了它' null'然后将其更改为“不为空”'当我收到错误。没有区别。

1 个答案:

答案 0 :(得分:0)

不确定该块在哪里,但让我看看这是否是你需要的。这样就完成了帖子中的所有内容,只不过是添加了一个外键约束。

create table Statuses
(
    StatusID int identity not null primary key clustered
    , StatusName varchar(50) not null
)

create table MainTable
(
    SomeColumn int identity
    , SomeValue varchar(50)
)

insert Statuses
select 'Status1' union all
select 'Status2' union all
select 'Status3'

insert MainTable
select 'Main table data 1' union all
select 'Main table data 2' union all
select 'Main table data 3'

select *
from Statuses

select *
from MainTable

--This should be what you state you have. Two tables with no foreign keys

--Now we add the new column
alter table MainTable
add StatusID int null

--Next we add our new foreign key constraint
alter table MainTable
add constraint fk_StatusMainTable foreign key (StatusID) references Statuses(StatusID)

--we need to populate the new column
update MainTable
set StatusID = 2 
where SomeColumn = 1

--There is no row in MainTable with a StatusID of 3 so this will work
delete from Statuses where StatusID = 3

--You cannot delete StatusID 2 because it violates the foreign key
delete from Statuses where StatusID = 2

--You cannot set the StatusID to 42 because it does not exists in the Statuses table
update MainTable
set StatusID = 42
where SomeColumn = 2

drop table MainTable
drop table Statuses