Inserting new record and skip if foreign key conflict in sql server 2008 R2 - sql

I have the problem similar to this one SQL Server foreign key conflict in a multi values statement? However, in sql server 2008.
While I am reading data from csv file, there is some id already not exist in parent and thus return this error:
INSERT statement conflicted with the FOREIGN KEY constraint
May I know if there is a way similar to MySQL insert ignore. Such that I can simply skip the problematic data.
I accept that if there is no method other than creating a stored procedure with a new temp table (insert into a table without foreign key first, and then re-insert with where foreign_id exists in (select id from parent)).
As I really cannot find any in documentation, asking for ensuring I didn't miss anything.

One general solution which comes to mind would be to temporarily turn off the foreign key constraints, and do the insert. Then, afterwards, you may run a cleanup script/query to remove or rectify child records which are pointing to parents which do not exist. Once your data is in good shape, then turn on the foreign key constraints again.
Read How can foreign key constraints be temporarily disabled using T-SQL? to learn how to disable/enable a foreign key constraint for a single table:
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint -- disable
ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint -- enable

Related

Adding foreign key fails unless data is first removed and reinserted after

I have an odd issue with foreign keys. I am trying to perform the following query:
ALTER TABLE [GroupMember] FOREIGN KEY ([Group]) REFERENCES [Group]([GUID])
Which gives me the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__GroupMember__Group__0D25C822". The conflict occurred in database "x", table "dbo.Group", column 'GUID'.
I then verified the existing things, which I have confirmed are all ok:
Referenced table (dbo.Group) has a defined PRIMARY KEY on [GUID] column
Referencing table (dbo.GroupMember) has no [Group]-values which do not exist in [GUID]-column of dbo.Group-table
No similarly referencing foreign keys exist already
From here on, I experimented. Taking some rows in and out, wiping the table, truncating the table. What I can conclude so far:
If I wipe the referencing table using DELETE FROM [GroupMember]; then try to apply the FK constraint, I receive the same error message
If I truncate the referencing table using TRUNCATE TABLE [GroupMember];, I can apply the FK constraint without errors. Additionally, I am able to reinsert the exact same data after applying the FK constraint, without problems.
From this I can conclude that the data itself is not the problem. Can anyone make sense of this? Why am I able to apply the constraint after truncating the table, but not after deleting all records?
If you are using Microsoft SSMS check whether unchecking "Prevent saving changes that require table re-creation" solves the problem. You'll find this in Options > Designers > Table and Database Designers.
I have had similar issues that have been resolved by this. Let me know if it works or not.
Good luck.

MS SQL Server - What is the value of WITH CHECK in a foreign key constraint?

When I have SQL Server Management Studio generate a table creation script for me, the foreign key constraints are a bit different than how I would write them.
Here is one:
ALTER TABLE [dbo].[GeoBytesCountries]
WITH CHECK
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
FOREIGN KEY ([MapReferenceId])
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO
ALTER TABLE [dbo].[GeoBytesCountries]
CHECK CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
GO
I would write this foreign key constraint without "WITH CHECK" and the 2nd "CHECK CONSTRAINT" statement and expect to get the same functionality.
Can someone explain to me the value of the using "WITH CHECK" and a separate "CHECK CONSTRAINT" statement when you are writing a foreign key constraint for a table?
Or is the code below completely / functionally equivalent to the code above?
ALTER TABLE [dbo].[GeoBytesCountries]
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
FOREIGN KEY ([MapReferenceId])
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO
The way I see it, the two step approach allows you to at least keep more "bad" data from getting in assuming the with check part fails. That is, your constraint will exist and apply to DML from that point forward, but you may have to do some cleanup on your existing data to make it a trusted constraint.

Sql Server 2008 Create Foreign Key Manually

I have inherited an old database which wasn't designed very well. It is a Sql Server 2008 database which is missing quite a lot of Foreign Key relationships. Below shows two of the tables, and I am trying to manually create a FK relationship between dbo.app_status.status_id and dbo.app_additional_info.application_id
I am using SQL Server Management Studio when trying to create the relationship using the query below
USE myDatabase;
GO ALTER TABLE dbo.app_additional_info
ADD CONSTRAINT FK_AddInfo_AppStatus FOREIGN KEY (application_id)
REFERENCES dbo.app_status (status_id)
ON DELETE CASCADE
ON UPDATE CASCADE ;
GO
However, I receive this error when I run the query
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"FK_AddInfo_AppStatus". The conflict occurred in database
"myDatabase", table "dbo.app_status", column 'status_id'.
I am wondering if the query is failing because each table already contains approximately 130,000 records?
Please help.
Thanks.
The error is occuring because there is a value in dbo.app_additional_info.application_ID that is not in dbo.app_Status.Status_ID. Unless the naming convention is seriously messed up you are trying to add a relationship to unrelated columns, why would application_ID reference status_ID?
I expect that dbo.App_Additional_Info.Application_ID should be referencing dbo.Application.Application_ID (Guessing at the table and column names slightly) so you would want this:
USE MyDatabase
GO
ALTER TABLE dbo.App_Additional_Info
ADD CONSTRAINT FK_App_Additional_Info_Application_ID (Application_ID)
REFERENCES dbo.Application (Application_ID)
ON DELETE CASCADE
ON UPDATE CASCADE;

Inserts conflict with the foreign key constraint but it is inserted

I am trying to insert a row in a SQL Server 2005 database and I'm getting a foreign key constraint violations.
When I look in the database I see the record that I was trying to insert (and is in conflict with the FK). I was under the impression that records that fail a FK are not inserted.
Is there a way that this could happen?
Regards,
Bas Hendriks.
So it seems that the DBA'er of this particular database has set the Enforce Foreign Key Constraint property to "No". It's beyond me why.
Thanks for the hint Lamak!

What is the equivalent effect to Truncating a table, when the table is referenced by a foreign-key

Straight out of the MSDN docs for Sql Server 2005:
You cannot use TRUNCATE TABLE on tables that:
Are referenced by a FOREIGN KEY constraint.
Participate in an indexed view.
Are published by using transactional replication or merge replication.
I want the effect of a TRUNCATE (specifically the fact that it resets IDENTITY type columns), but I can't use one in my case because my table is referenced by a foreign-key elsewhere in the database.
Update: This is for a testing configuration where I am clearing out the referencing table as well, so foreign-key integrity is a non-issue.
What other ways are there to get around this?
You can delete all the rows and then do a DBCC CHECKIDENT (Tablename, RESEED, 0) to reset the identity seed
But again DELETE is fully logged while TRUNCATE is minimally logged and will be many times faster
Another option is to drop the foreign key constrains then do a truncate and then recreating the foreign key constraints
The fact that it is refernced by a foreign key is the clue you need to not truncate a table or you would be creating orphaned records. This is why truncate table is not allowed if a foreign key exists.
The correct process is to first delete the refernced records, if any, then drop the FK constraint, then truncate the table then reinstate the fk constraint. If you skip step one, you will create a data integrity nightmare where the record pointing to oldid 100 is not pointing to the new record that happens to get assigned to 100 and it isn;t the record it should match to.
You can drop the foreign key, truncate the table, and then recreate the foreign key.
You will need to drop the constraint, trunc the table, and then add the constraint back. However, you should be very careful with this. If there are rows in the table that you are dropping the FK reference to you will not be able to add it until those rows are deleted or the FK column in the other table is clear.