Sql Server 2008 Create Foreign Key Manually - sql

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;

Related

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

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

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.

Modify existing Foreign Key to include Update Cascade

I'm using SQL Server 2008 R2 & SQL Azure database for my environment. I have defined primary keys and foreign keys and their constraint names too. I now want to change the primary key values but I cannot do it since the foreign keys not allowing me to do since they are not specified as UPDATE CASCADE when the PK-FK relationship / constraints were defined.
Is there any SQL statement by which in the existing constraints I can include the UPDATE CASCADE and henceforth change my primary key values?
As far as I know, you can only define those attributes like ON UPDATE CASCADE when you create the constraint.
So you'll need to drop the constraint and re-create it with the proper attributes.
If you need to drop the primary key constraint, you'll have to
drop all FK constraints referencing that PK
then drop and re-create your PK constraint
and in the end, re-create the dropped FK constraints

Foreign Keys left after table deletion?

So here's an interesting one for you... I am working on copying one entire database (db1) and structure over from one database to another (db2), and before doing so I decided to try and drop all tables from the db2. I did the usual sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAING ALL' and then sp_msforeachtable 'DROP TABLE ?' and much to my dismay, it deleted all save for maybe 6 tables. These tables seemed to still have foreign key references to them. I did a search and found this SQL DROP TABLE foreign key constraint which showed me how to find and then try to delete those foreign key references.
This is the interesting part: upon attempting to delete them using that information, I have been told that ssms cannot find the object because it does not exist or I do not have permission. The foreign key reference is coming from a table that I have previously deleted.
How is that possible? And how on earth do I progress from here?
I don't know what you mean by them in "upon attempting to delete them". If you were trying to delete the foreign key from the system tables, that would definitely be a mistake.
My guess is you can just drop those last 6 tables now.
Suppose we have two tables A and B
create table A (a int)
create table B(b int, foreign key (b) references (A.a))
and we try to drop the tables. drop table A will fail, because B references it with a declared foreign key. But we can freely drop table B, because A doesn't care if it's no longer being referenced.
So after the first pass, one DROP failed and one succeeded, leaving one table, now with no FK references. Try again and, voila!, drop table A now works.

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!