Two Tables with cascade delete


Two Tables with cascade delete



I have two tables:


[tbl_Records_DR] PK DAutoID.
[tbl_Records_DR_Explain] PK DRefer_ID



I'm creating my tables programmatically (only).



Here's what I currently have that works well creating the tables:


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;")



Thanks,
ADawn





Do you already have the field defined in tbl_Records_DR_Explain that points to tbl_Records_DR? Microsoft Docs has detailed information on creating foreign keys: docs.microsoft.com/en-us/sql/relational-databases/tables/…
– Zack
Jun 29 at 16:58


tbl_Records_DR_Explain


tbl_Records_DR





Why are you creating tables in a program like this? Seems like a lot of effort to write code that can't run more than once.
– Sean Lange
Jun 29 at 19:21




2 Answers
2



Use ALTER TABLE to change one of this tables and add FOREIGN KEY. Hope i help you


ALTER TABLE


FOREIGN KEY



I think this is what you want:


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



Edit


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





Do I ALTER TABLE after I create it? Or is there a way to do what you suggest when the table is created?
– tropicwhisper
Jun 29 at 17:37






Added edit to include the FK in the original creation of table instead of altering table after
– Ian-Fogelman
Jun 29 at 17:43






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift