SQL Server 2008 foreign key confilict - sql-server

We have got table which has many rows. I want create foreign key between these two tables but
I get the following error.
'CMEvent' table saved successfully;
'BaseEvent' table
Unable to create relationship 'FK_CMEvent_Oid'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_CMEvent_Oid". The conflict occurred in database "CMO_RestoredData", table "dbo.BaseEvent", column 'Oid'.`

I was able to duplicate this error when I had a row in the CMEvent table that did not exist in BaseEvent.
Try running this query:
SELECT *
FROM CMEvent c
WHERE NOT EXISTS (
SELECT *
FROM BaseEvent
WHERE oid = c.oid )
If you get any rows back, these will have to be deleted before you can apply the foreign key constraint.
If you need to keep these orphaned rows, you can use WITH NOCHECK to only apply the constraint to new rows.

Related

Table with multiple relations to a single primary key

Is it possible to create multiple relations from one table, to another table?
I have a table containing purchases, each of these purchases have a origin_country and a destination_country.
I would like to have relations (as foreign keys) to a single PK on a table from these two columns from the same table.
i have tried the following queries:
alter table Purchases
add constraint FK_Purchases_OriginCountries
foreign key (FK_OriginCountryCode) references dbo.countries
go
alter table Purchases
add constraint FK_Purchases_DestinationCountries
foreign key (FK_DestinationCountryCode) references dbo.countries
go
But end up getting a conflict, I can't however find documentation that this is not possible...
[23000][547] The ALTER TABLE statement conflicted with the FOREIGN KEY
constraint "FK_Purchases_DestinationCountries". The conflict occurred
in database "Market", table "dbo.countries", column 'ID'.
Is this relationship intentionally not possible, or did i just make a mistake?
Thank you
Yes you can.
The error is not a result of trying to create two foreign keys back to a single table, that's perfectly fine. Try running this to see it work:
create table t(i int primary key);
create table u
(
j int foreign key references t(i),
k int foreign key references t(i)
);
The problem you have is that you have some data in your Purchases table where the value in the column on which you are trying to create the foreign key does not exist in the countries table's ID column.
To find them run a query like this:
select p.*
from dbo.purchases p
where not exists
(
select *
from dbo.countries
where ID = p.FK_DestinationCountryCode
)
Note that I think your column names are a little weird here, You shouldn't call a column FK_DestinationCountryCode just because it has a foreign key on it, and a "code" is not the same kind of thing as an "ID". Your purchases table's columns should probably be called DestinationCountryID and OriginCountryID.

SQL Server foreign key contsraint preventing insert, where no conflict exits

I have 2 tables, and I have just done an insert of about 1,000,000 rows. I turned off foreign key constraints , but I have an error when I try and reinstate them with
ALTER TABLE ForexRebatesNow.dbo.Transactions WITH CHECK CHECK CONSTRAINT ALL
I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Transactions_RebateAccounts". The conflict occurred in database "ForexRebatesNow", table "dbo.RebateAccounts", column 'Id'.
So I go to look for RebateAccountId that does not have a corresponding Id in the RebateAccounts table
SELECT Id
FROM ForexRebatesNow.dbo.RebateAccounts
WHERE Id NOT IN (SELECT RebateAccountId
FROM ForexRebatesNow.dbo.Transactions)
But this returns zero rows, so in my mind that conflict does not exist.
Am I missing something here?
EDIT
The relationship between RebateAccounts and Transactions is One to Many. RebateAccountId is a Nullable int on Transactions table as not allTransactions will have an associated RebateAccount, but any RebateAccount can have many Transactions
As you have not provided the relations between the two tables, I assume that there is a One-to-Many relation between RebateAccounts and Transactions Table. If I'm right then I guess you are checking the conflict in an opposite way. Your foreign key in in the dbo.Transactions table but you are checking it with the dbo.RebateAccounts table.
Try the following query to find the conflict.
SELECT * FROM Transactions WHERE RebateAccountId NOT IN (SELECT Id FROM RebateAccounts)
If any row shows up then that row has an account id that does not belong to any account. That's where your conflict is.
Hope it helps.

Adding constraint conflicts with itself, even though it doesn't exist yet

I'm adding delete cascading to a Table. The Clone table has a column DeviceID that is a foreign key to the Device table's DeviceID column. So the SQL script drops the original FK constraint, and attempts to add the new one:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device'
)
BEGIN
ALTER TABLE Clone
DROP CONSTRAINT FK_Clone_Device
END
IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device_Cascade'
)
BEGIN
ALTER TABLE Clone
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE
END
When I run this script, I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Clone_Device_Cascade". The conflict occurred in database "DevelopmentDB", table "dbo.Device", column 'DeviceID'.
Maybe I'm misunderstanding the error message, but it sounds like it's conflicting with itself. I'm confused that it happened on the Device table though.
There is an index in the Clone table on DeviceID. Would that matter?
This is on SQL SERVER R2 (Azure)
Sounds like you currently have data in the table that would violate the FK you are trying to create. One way to test this is to add "WITH (NOCHECK)" to the ALTER TABLE statement and see if it lets you create the constraint.
If it does let you create the constraint with NOCHECK, you can either leave it that way and the constraint will only be used to test future inserts/updates, or you can investigate your data to fix the FK violations.
So your example would be:
ALTER TABLE Clone WITH NOCHECK
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE

Foreign key linked with primary key in same table

I have a table Categories with columns Id, ParentId (for "subcategories" whom can have any level of nesting) and some other. Using SQL Server 2012 I can't make foreign key in same table, FK_Categories_Categories (Id -> ParentId).
Error message is
'Categories' table
- Unable to create relationship 'FK_Categories_Categories'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories". The conflict occurred in database "pokupaykadb", table "dbo.Categories", column 'Id'.
That needs for cascade deletion of subcategories. What solution can be? It's desirable to be a some property, like cascade deletion from another table by foreign key
http://i.stack.imgur.com/kXiMS.png
If there are orphaned records that does not meet your constraint criteria - delete them before creating the foreign key.
Usually there are few records which doesn't go by the new constraint and that the DBMS doesn't allow to create the constraint.
In the case of orphaned values, the first occurrence is provided in the error label with the value that is orphaned.
It would certainly have helped to see what code you have tried to execute.
Below is a valid table definition :
CREATE TABLE dbo.Categories
(
Id int NOT NULL IDENTITY(-2147483648, 1)
CONSTRAINT PK_Categories PRIMARY KEY
, ParentId int NOT NULL
CONSTRAINT FK_Categories_ParentId
FOREIGN KEY (ParentId) REFERENCES dbo.Categories
)

No foreign key restraints on a temporary table? SQL Server 2008

I know that a a temporary table will only exist for as long as a session of SQL Server is open, but why can't you have foreign key restraints on them?
Imagine this scenario: You create a foreign key relationship from your temp table to a concrete table's key. One of the restrictions on a foreign key relationship is that you cannot delete a row from a key table that is depended upon by your temp table. Now, generally when you create foreign key relationships you know to delete the dependent table rows before deleting the related rows in the key table, but how does a stored procedure or any other call into the database know to delete rows from your temp table? Not only is it impossible to discover spurious foreign key dependencies, other sessions could not reach your temp table even if it could discover the relationship. This leads to spurious failures in delete statements as foreign key constraints restrict the key table for dependent rows.
You can create foreign keys between tables in tempdb. For example, try this:
use tempdb
create table parent
(
parent_key int primary key clustered
)
create table child
(
child_key int primary key clustered,
child_parent_key int
)
alter table child add constraint fk_child_parent foreign key (child_parent_key) references parent(parent_key)
insert into parent(parent_key) select 1
insert into child(child_key, child_parent_key) select 1, 1
insert into child(child_key, child_parent_key) select 2, 2 -- this fails because of the FK constraint
drop table child
drop table parent
Could be because you can't have cross-database foreign key constraints and temp tables technically are created in the TempDB database.
Unless you mean between a temp table and another temp table... but really there's lots of issues you get into when you talk about those kind of constraints on a temp table.

Resources