Modify Foreign Key Relationships in TSQL - sql-server

I would like to see some example how to modify foreign key relationship in TSQL because it is missing here http://technet.microsoft.com/en-us/library/ms175493.aspx
Actually I want to apply delete rule Cascade.
Should it be like?
ALTER TABLE Email MODIFY
CONSTRAINT FK_EmailContact_Email
ON DELETE CASCADE
Thank you!

I found how I can do it
GO
ALTER TABLE EmailContact DROP
CONSTRAINT FK_EmailContact_Email
GO
ALTER TABLE EmailContact ADD
CONSTRAINT FK_EmailContact_Email
FOREIGN KEY (EmailId)
REFERENCES Email (Id)
ON DELETE CASCADE

Related

Can We Create On Delete Cascade on exiting foreign Key

Can we create On Delete Cascade on an existing Foreign Key?
I know we can create from SQL design of table going to relationships But I want to do this with the script query?
I also not want to drop foreign key first and then create the foreign key with on delete cascade, I not want this.
There is no ALTER CONSTRAINT syntax. If you have created a CONSTRAINT and you need to change it, you need to DROP the CONSTRAINT and then CREATE it again; there is no work around for this.
In this case, using the definition in the comments, you would need to do:
ALTER TABLE [dbo].[HL7_Rx_Resident_NonVerified] DROP CONSTRAINT [FK_HL7_Rx_Resident_NonVerified];
GO
ALTER TABLE [dbo].[HL7_Rx_Resident_NonVerified] WITH CHECK
ADD CONSTRAINT [FK_HL7_Rx_Resident_NonVerified]
FOREIGN KEY ([MedicationId])
REFERENCES [dbo].[RxOrder_Resident_NonVerified] ([Id]) ON DELETE CASCADE;
GO

cascade foreign key on multiple columns

I am trying to create UPDATE CASCADE Foreign key reference to a table using below scripts.I am getting error saying it may cause cycles or multiple cascade paths.
ALTER TABLE STA_STATIONARY_REQUEST_MASTER WITH CHECK ADD CONSTRAINT [FK_STA_STATIONARY_REQUEST_MASTER_REQUESTOR_ID] FOREIGN KEY([REQUESTOR_ID])
REFERENCES STA_EMPLOYEE_MASTER ([EMPLOYEE_ID])
ALTER TABLE STA_STATIONARY_REQUEST_MASTER WITH CHECK ADD CONSTRAINT [FK_STA_STATIONARY_REQUEST_MASTER_CREATED_BY] FOREIGN KEY([CREATED_BY])
REFERENCES STA_EMPLOYEE_MASTER ([EMPLOYEE_ID])
But when I am creating using below scripts it is created successfully.But still i am not able to update the employee id.
ALTER TABLE STA_STATIONARY_REQUEST_MASTER ADD CONSTRAINT
FK_STA_STATIONARY_REQUEST_MASTER_EMP1
FOREIGN KEY (REQUESTOR_ID) REFERENCES STA_EMPLOYEE_MASTER(EMPLOYEE_ID),
FOREIGN KEY (CREATED_BY) REFERENCES STA_EMPLOYEE_MASTER (EMPLOYEE_ID)
ON UPDATE CASCADE
Please help.

Delete foreign key with primary key reference

I tried many forums but was not satisfied - I have a table that has a primary key and foreign key relation.
I have to delete table rows with primary key so I need to remove the constraints before deleting.
I used:
delete from [docd_metadata].[docd_metadata].[STATEMENT_IMAGES]
where [statement_image_id]= 05291520275
I got error:
The DELETE statement conflicted with the REFERENCE constraint "fk_stmnt_image_StmntImageId". The conflict occurred in database "docd_metadata", table "docd_metadata.STATEMENT_CAMPAIGN", column 'STATEMENT_IMAGE_ID'.
so I tried :
ALTER TABLE[docd_metadata].[docd_metadata].[STATEMENT_IMAGES]
DROP CONSTRAINT [fk_stmnt_image_StmntImageId]
Now I am getting :
Constraint 'fk_stmnt_image_StmntImageId' does not belong to table 'STATEMENT_IMAGES'
Schema:
Also:
Any suggestion please?
If you really closely read the error message, it's clear that the FK constraint is on table docd_metadata.STATEMENT_CAMPAIGN and not on STATEMENT_IMAGES - so therefore, you must use this SQL to drop the FK constraint:
ALTER TABLE [docd_metadata].[STATEMENT_CAMPAIGN]
DROP CONSTRAINT [fk_stmnt_image_StmntImageId]
The FK goes from table [docd_metadata].[STATEMENT_CAMPAIGN] (column STATEMENT_IMAGE_ID) to [docd_metadata].[STATEMENT_IMAGES] - one table has the primary key, which another table references via its foreign key.

Unable o create foreign key with the help of code

I am using the code below, but unable to create the foreign key.
USE project;
GO
ALTER TABLE Sale.TempSalesReason
ADD CONSTRAINT FK_TempSale_SalesReason FOREIGN KEY (TempID)
REFERENCES Sale.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO
Please go through the link below and check if you are able to create the foreign key relationships in SQL server.
http://technet.microsoft.com/en-us/library/ms189049.aspx

How to DELETE without ON DELETE CASCADE (conflict REFERENCE constraint)

I have a gigantic legacy database with a table that has multiple foreign keys pointing to one other table and with not a single cascade in sight, similar to sample tables below:
create table Users (
Id int primary key identity,
Name varchar(max)
)
create table Products (
Id int primary key identity,
Name varchar(max),
CreatedBy int foreign key references Users(Id),
UpdatedBy int foreign key references Users(Id)
)
insert into Users values('Bar')
insert into Users values('Baz')
insert into Products values('Foo', 1, 2)
I need to be able to to delete some of the old data, but it of course throws reference exceptions:
delete from Users where Name='Bar'
The DELETE statement conflicted with the REFERENCE constraint "FK__Products__Create__1AD3FDA4". The conflict occurred in database "Foo", table "dbo.Products", column 'CreatedBy'.
Due to the sheer complexity of the database I can't predelete all of the references, so I'm trying to add temporary foreign keys programmatically with cascades set to resolve them. However, for this particular table that has multiple foreign keys to one other table, this results in cycles or multiple cascade paths on the second UpdatedBy alter:
alter table Products add foreign key (CreatedBy) references Users(Id) on delete cascade
alter table Products add foreign key (UpdatedBy) references Users(Id) on delete cascade
Introducing FOREIGN KEY constraint 'FK__Products__Update__1DB06A4F' on table 'Products' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
How can I make delete from Users where work while maintaining referential integrity, either by somehow getting around multiple cascade path issues or otherwise?
Personally I would not do this (I would pre-delete all the referenced data and manually check the integrity). See: Can foreign key constraints be temporarily disabled using T-SQL?
Quote:
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
Delete your data once the constraints are disabled, but remember to turn them back on again afterwards!
-- enable all constraints
EXEC sp_msforeachtable #command1="print '?'", #command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
Also note that the stored procedure sp_msforeachtable is undocumented and may disappear in future releases of SQL Server.
If you'd rather not blanket-disable constraints (perhaps you have a list of the tables that apply) then simply disable them as you can see in the code above.
ALTER TABLE [Products] NOCHECK CONSTRAINT ALL
DELETE FROM [Users] where Name='Bar'
ALTER TABLE [Products] WITH CHECK CHECK CONSTRAINT ALL
All credit goes to kristof's answer. Please up vote!

Resources