两个表与级联删除

时间:2018-06-29 16:46:48

标签: sql sql-server

我有两个表:

[tbl_Records_DR] PK DAutoID.
[tbl_Records_DR_Explain] PK DRefer_ID
  1. 我想在这些表之间创建一个外键。
  2. 从[tbl_Records_DR]中删除记录时,我希望能够级联删除。

我正在以编程方式创建表(仅)。

这是我目前拥有的能很好地创建表格的东西:

CREATE TABLE [tbl_Records_DR] ( " _
& "[DAutoID] int IDENTITY (1,1) PRIMARY KEY NOT NULL " _
& ", [Hub_Unique_Name] nvarchar(30) DEFAULT ''  NULL " _
& ", [DStatus] nvarchar(30) DEFAULT ''  NULL " _
& ", [DDate] datetime NULL " _
& ", [DTime_Start] datetime NULL " _
& ", [ReportCreatedFrom] nvarchar(5) DEFAULT 'DR'  NULL);")

CREATE TABLE [tbl_Records_DR_Explain] ( " _
& "[AutoID] int IDENTITY (1,1) NOT NULL " _
& ", [DRefer_ID] int PRIMARY KEY  NOT NULL " _
& ", [DExplain] nvarchar(700) DEFAULT ''  NULL " _
& ", [ImportCompleted] bit DEFAULT 0 NULL;")

谢谢, 黎明

2 个答案:

答案 0 :(得分:1)

使用ALTER TABLE更改此表之一并添加FOREIGN KEY。希望我能帮到你

答案 1 :(得分:0)

我想这就是你想要的:

ALTER TABLE [tbl_Records_DR_Explain]
ADD CONSTRAINT fk_AutoID
    FOREIGN KEY ([DRefer_ID])
    REFERENCES [tbl_Records_DR] ([DAutoID])
    ON DELETE CASCADE;

编辑

CREATE TABLE [tbl_Records_DR_Explain] (
[AutoID] int IDENTITY (1,1) PRIMARY KEY NOT NULL 
, [DRefer_ID] int  NOT NULL 
, [DExplain] nvarchar(700) DEFAULT ''  NULL 
, [ImportCompleted] bit DEFAULT 0 NULL
    CONSTRAINT fk_AutoID
    FOREIGN KEY (DRefer_ID)
    REFERENCES [tbl_Records_DR] ([DAutoID])
    ON DELETE CASCADE
    )

http://rextester.com/NZH15043