how to add foreign key constraint, SQL Server - sql-server

I have a registration table with primary key RegId. I have another table named Users, also contain RegId as Foreign key.
When I delete one RegId from registration, I have to delete RegId from Users. Can anybody help?

Define the foreign key with "ON DELETE CASCADE".
You can do this is in T-SQL or in design view in SSMS

You could to alter the main table with a constraint saying that a Delete On Cascade must be done.
Based on your inputs, something similar to this:
ALTER TABLE dbo.Registration
ADD CONSTRAINT FK_Registration_Users_Cascade
FOREIGN KEY (RegId) REFERENCES dbo.Users(RegId) ON DELETE CASCADE
Also, you can achieve this with the SQL Management Studio selecting your table (in Design mode) and go to Relationships option. There you'll see the "INSERT and UPDATE specifications" button for setting this things.
MSDN Article
Cascading Referential Integrity Constraints

Related

Migrating a self referencing table using Azure Data Factory

I am trying to migrate a table which has 2 colums.
Id - Primarky key
Parent ID - Foreign key populated by the value above (Id).
(So basically the FK is in the same table)
When I migrate this, I get the following error.
"The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint"
Please let me know how to deal with this.
Thanks in advance
Disable the foreign key constraint first. Then migrate your data. And afterwards you can enable the constraint again.
ALTER TABLE Purchasing.PurchaseOrderHeader
NOCHECK CONSTRAINT FK_PurchaseOrderHeader_Employee_EmployeeID;
ALTER TABLE Purchasing.PurchaseOrderHeader
CHECK CONSTRAINT FK_PurchaseOrderHeader_Employee_EmployeeID;
Disable foreign key constraints with INSERT and UPDATE statements

Is there a way to turn off foreign key constraints at database level?

We need to use existing sql to create a bunch of tables and this sql includes ALTER TABLE statements to add in foreign keys. When we run this block of SQL, however, errors are thrown because tables needed for the foreign keys haven't been created yet (they are later on in the block of SQL).
Is there a way to turn off foreign key constraints at database level? (versus at table level) We just need to create all of the tables and foreign keys and then turn it back on.
Thanks!
To disable foreign key constraints when you want to truncate a table:
Use FOREIGN_KEY_CHECKS
SET FOREIGN_KEY_CHECKS=0;
and remember to enable it when you’re done:
SET FOREIGN_KEY_CHECKS=1;
Or you can use DISABLE KEYS:
ALTER TABLE table_name DISABLE KEYS;
Again, remember to enable if thereafter:
ALTER TABLE table_name ENABLE KEYS;
Note that DISABLE KEYS does not work on InnoDB tables as it works properly for MyISAM.
Use ON DELETE SET NULL
If you don’t want to turn key checking on and off, you can permanently modify it to ON DELETE SET NULL:
--Delete the current foreign key first:
ALTER TABLE table_name1 DROP FOREIGN KEY fk_name1;
ALTER TABLE table_name2 DROP FOREIGN KEY fk_name2;
--Then add the foreign key constraints back
ALTER TABLE table_name1
ADD FOREIGN KEY (table2_id)
REFERENCES table2(id)
ON DELETE SET NULL;
ALTER TABLE tablename2
ADD FOREIGN KEY (table1_id)
REFERENCES table1(id)
ON DELETE SET NULL;

SQL Server - ALTER query can create FK relationships, but cannot view them?

I'm stumped on whether I have written the correct syntax to create a foreign key.
I used SQL Server 2012 Express.
If I run a ALTER query to set a foreign key relationship between two table, it works fine, no errors occured. However, if I right-click the table where the FK was created, I don't see any relationships.
This is the ALTER query I have wrote. It creates a relationship between Employers and Employees with EmployerID as a FK.
USE demodemo;
BEGIN TRAN t1
ALTER TABLE Employees
WITH check
ADD CONSTRAINT Employees_EmployerID_FK FOREIGN KEY
(EmployerID) REFERENCES Employers(ID);
GO
The command was executed 'successfully'.
However, if I right click the table, Employees, and select 'Relationships'.
No foreign keys relationships can be seen.
I thought writing the above ALTER query would be the equivalent of creating a FK relationship via the 'Relationships' gui.
Despite having no issues in creating foreign key relationships, I just cannot see them at all.
What could I be doing wrong?
Is my ALTER query correct?
What is the ALTER syntax equivalent to allow me to view the "selected relationships"?
Your DML is missing COMMIT. Also, right click and refresh after executing the SQL
Raj

Enable foreign key with Check existing data

I love foreign keys, but I'm running into one problem with them. I have a conversion program where I am disabling foreign keys to tables. The reason I'm doing this is so that I can reconvert all records in the main table, but leave the other tables dependent on that one untouched without having to reconvert them every time because they are HUGE.
I'm using these commands to disable and re-enable the foreign keys:
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint
However, after I re-enable the constraint "Check Existing Data on Creation or Re-Enabling" is still set to No. I understand that it is set to No because I disabled the constraint, but by doing this it altered my database schema, which I don't like. I thought this would be considered re-enabling the constraint and would check the existing data, but apparently not.
Is there no way to change this with the ALTER TABLE command? I know I can if I drop the constraint and recreate it, but I'm not about to write the script to recreate every foreign key I have and maintain that.
I'm using SQL Server 2008 R2.
To re-enable a constraint:
-- Enable the constraint
ALTER TABLE MyTable
WITH CHECK CHECK CONSTRAINT MyConstraint
GO
Note: you have to specify CHECK twice to force a check that all foreign key values are valid.
FOREIGN KEY and CHECK constraints that are disabled are marked
is_not_trusted.These are viewable in the sys.check_constraints and
sys.foreign_keys catalog views. This means that the constraint is no
longer being verified by the system for all rows of the table. Even
when you re-enable the constraint, it will not reverify the existing
rows against the table unless you specify the WITH CHECK option of
ALTER TABLE. Specifying WITH CHECK marks the constraint as trusted
again.
Ref.: Guidelines for Disabling Indexes and Constraints
As noted in comments (for search engines), this corresponds to
sys.foreign_keys.is_not_trusted
in the catalog view

SQL Server update primary key that's also a foreign key in two tables

I need to update the primary key for a record but it's also the foreign key in two other tables. And I need the updated primary key to be reflected in the child tables as well.
Here is my query and the error:
begin tran
update question set questionparent = 10000, questionid= 10005 where questionid = 11000;
Error 9/4/2009 10:04:49 AM 0:00:00.000 SQL Server Database Error: The UPDATE statement conflicted with the REFERENCE constraint "FK_GoalRequirement_Question". The conflict occurred in database "numgmttest", table "dbo.GoalRequirement", column 'QuestionID'. 14 0
I don't remember how to go about doing this so that's why I'm here. Any help?
Are your relationships using
ON UPDATE CASCADE
If they are then changing the key in the primary table will update the foreign keys.
e.g.
ALTER TABLE Books
ADD CONSTRAINT fk_author
FOREIGN KEY (AuthorID)
REFERENCES Authors (AuthorID) ON UPDATE CASCADE
You may:
disable enforcing FK constraints temporarily (see here or here)
update your PK
update your FKs
enable back enforcing FK constraints
do it all within a transaction and make sure that if transaction fails, you roll it back properly and still enforce the FK constraints back.
But... why do you need to change a PK? I hope this is an action that is executed rarely (legacy data import or something like that).
If you would like to set the Cascade rule graphically then Set Cascade Rule on SQL Management Studio
Open table in design mode
Click Relationship button from top toolbar
Select the required FK relations (one by one)
Right Side - Expand INSERT or UPDATE Specification
Change the UPDATE Rule to - Cascade
Close and Save, Done!
(Tried on SQL 2008)
As I'm not too confident disabling FK constraints, I prefer too :
Duplicate the row with the old PK with one with the new PK
Update the FKs
Delete the row with the old PK
Advantage : No constraint violated during the process.
Go to foreign Key Relations of each child tables and on Insert and Update specification change delete and update rules to cascade.
create a New row with the same data and a different primary key.
update all the children tables.
remove the row that you repeated its data
And its done.

Resources