Disable Foreign key constraint on a table? - sql

Can i temporarily disable a foreign key constraint. How do i do this?

To temporarily disable a constraint (foreign keys are constraints):
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint
To re-enable a constraint
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint

Incidentally, this is why you need "Alter table" permissions when you BCP or Bulk Insert data into a table. Using the default configuration, check constraints and foreign keys are not checked.

Related

How to add multiple foreign keys with nocheck for each one?

i need to create multiple fk for diffrent fields with nocheck for each fk,
all the examples i see is only for 1 fk at a time,
i need something like this :
ALTER TABLE contact
WITH NOCHECK ADD CONSTRAINT [FK_check5]
FOREIGN KEY (accountid) REFERENCES dbo.account ([accountid]),
WITH NOCHECK ADD CONSTRAINT [FK_check6]
FOREIGN KEY (roleid) REFERENCES dbo.role ([id])
the disabled must be on the create level and not after it
seperate your alter table statement into two
ALTER TABLE contact
WITH NOCHECK ADD CONSTRAINT [FK_check5]
FOREIGN KEY (accountid) REFERENCES dbo.account ([accountid]);
ALTER TABLE CONTACTS
WITH NOCHECK ADD CONSTRAINT [FK_check6]
FOREIGN KEY (roleid) REFERENCES dbo.role ([id]);
The 'NoCheck' will apply to all the constraints you add in the statement, you don't need to repeat it:
Example below (tested in SQL 2012):
CREATE TABLE account (accountid int, PRIMARY KEY (accountid))
GO
CREATE TABLE [role] (id int, PRIMARY KEY (id))
GO
CREATE TABLE contact (accountid int, roleid int)
GO
insert into contact values (1,1)
GO
ALTER TABLE contact
WITH NOCHECK
ADD
CONSTRAINT [FK_check5] FOREIGN KEY (accountid) REFERENCES [account] ([accountid])
,CONSTRAINT [FK_check6] FOREIGN KEY (roleid) REFERENCES [role] ([id])
If your intention is to only have the foreign key for ER diagramming, you can turn off enforcing of the constraint. See the below article for more information.
https://learn.microsoft.com/en-us/sql/relational-databases/tables/disable-foreign-key-constraints-with-insert-and-update-statements
as per the example provided in the article:
USE AdventureWorks2012;
GO
ALTER TABLE Purchasing.PurchaseOrderHeader
NOCHECK CONSTRAINT FK_PurchaseOrderHeader_Employee_EmployeeID;
GO
That being said, I would recommend that you NEVER do this in a production system on an ongoing basis. Foreign key constraints exist for a reason, to maintain data integrity. If you are inserting data in a way that violates foreign key constraints you may want to review your data design.

SQL Server - Insert and update specification (Foreign key relationship)

I just want to know if there is any way to write some function or stored procedure in sql server to change the delete rule programmatically?
Example: I have to change the delete rule from Cascade to none or vice versa but I don't want to do graphically.
Because I have to do quite often and want to revert it back to its initial stage.
You can't alter a foreign key constraint to change the cascade option, you will have to drop it and create it again with the option you want. Make sure to set it on a transaction as you don't want inconsistent data getting stuck in the middle of the change.
The alter commands of an example:
ALTER TABLE [SchemaName].[TableName] DROP CONSTRAINT [ConstraintName]
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD CONSTRAINT [ConstraintName]
FOREIGN KEY([ColumnName]) REFERENCES [SchemaName].[YetAnotherTableName]([ColumnName]) ON DELETE CASCADE;
Let's assume you have a foreign key already called fk_table1_table2 with cascade none.
You would have to drop the constraint and then recreate a constraint with cascade:
ALTER TABLE [dbo].[TableName] DROP CONSTRAINT [FK_Table1_Table2]
GO
ALTER TABLE [dbo].[TableName] WITH NOCHECK ADD CONSTRAINT [FK_Table1_Table2] FOREIGN KEY([Table2])
REFERENCES [dbo].[Table2] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[TableName] CHECK CONSTRAINT [FK_Table1_Table2]
GO
This is generated from ssms. You can do this like here:
You can right click on any Key and generate the code for you ;)

Alter a table to add a foreign key constraint with a default value

How do I alter a table to have a column a foreign key constraint with a default value?
In T-SQL if you're using SQL-Server, just be careful to put a real key for default.
Edit: As said in the comments, be careful that you really need a default value for a foreign key, there could be a design problem.
ALTER TABLE [tablename]
ADD CONSTRAINT [CK_columnname_default]
DEFAULT [your_default_value] FOR [columnname];
GO
ALTER TABLE [tablename]
ADD CONSTRAINT [FK_nameForeignKey] FOREIGN KEY (columnname)
REFERENCES [dbo].[oTable] (oTableID)
ON UPDATE CASCADE;
GO
Well I did the following and it worked for me:
ALTER TABLE Employee
ADD RegionID varchar(3)
CONSTRAINT [Default_Value_Region] default ('US') NOT NULL,
CONSTRAINT [FK_EMPLOYEE_Region] FOREIGN KEY([RegionID])
REFERENCES [dbo].[Region] ([Code])
GO

Is there a way of forcing sql INSERT or disabling foreign key check?

I just found out a SQL Server bug (described here). Now I am wondering, if there is any possibility of forcing an INSERT statement without performing foreign key checks? Like disabling this checks server-wide for few minutes, or somehow disabling (not deleting) FK's on specific tables?
ALTER TABLE [schema].[table] NOCHECK CONSTRAINT [constraint_name]
Then
ALTER TABLE [schema].[table] CHECK CONSTRAINT [constraint_name]
However, this results in your FK being not trusted, and when you re-enable the constraint it will take time to re-validate it.
Drop Constraint
ALTER TABLE Table_Name
DROP CONSTRAINT fk_ConstraintName
Drop the constraint once you have done the operation then create it again.
Disable Constraint
ALTER TABLE MyTable
NOCHECK CONSTRAINT fk_Constraint_Name
Enable Constraint
ALTER TABLE MyTable
CHECK CONSTRAINT fk_Constraint_Name
Check Disable Foreign Key Constraints with INSERT and UPDATE Statements:
To disable a foreign key constraint for INSERT and UPDATE statements
In Object Explorer, expand the table with the constraint and then
expand the Keys folder.
Right-click the constraint and select Modify.
In the grid under Table Designer, click Enforce Foreign Key
Constraint and select No from the drop-down menu.
Click Close.
or simple use this command:
ALTER TABLE tablename
NOCHECK CONSTRAINT fk_ConstraintName

How to Alter Constraint

SQL How to Alter Constraint
Below is 1 of my constraint
CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode),
I want to add in
ON DELETE CASCADE
to the constraint above.
How do i alter that existing constraint ACTIVEPROG_FKEY1 and add
ON DELETE CASCADE
to constraint ACTIVEPROG_FKEY1
Consider ACTIVEPROG_FKEY1 is at Table ACTIVEPROG
You can not alter constraints ever but you can drop them and then recreate.
Have look on this
ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;
and then recreate it with ON DELETE CASCADE like this
ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
ON DELETE CASCADE;
hope this help
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)