Invisible Foreign Key in SQL Server 2005 - sql-server

I have a script to update a database by checking for a foreign key's existence and, if it doesn't exist, creating it. It was generated by SQL Management Studio.
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblChangeRequestForecast_tblCostingCenter]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblChangeRequestForecast]'))
ALTER TABLE [dbo].[tblChangeRequestForecast] WITH CHECK ADD CONSTRAINT [FK_tblChangeRequestForecast_tblCostingCenter] FOREIGN KEY([CostingCenterID])
REFERENCES [dbo].[tblCostingCenter] ([CostingCenterID])
GO
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblChangeRequestForecast_tblCostingCenter]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblChangeRequestForecast]'))
ALTER TABLE [dbo].[tblChangeRequestForecast] CHECK CONSTRAINT [FK_tblChangeRequestForecast_tblCostingCenter]
GO
The script raises an error when it's run:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_tblChangeRequestForecast_tblCostingCenter". The conflict occurred in database "mydatabase", table "dbo.tblCostingCenter", column 'CostingCenterID'.
This is very mysterious. There is no trace of the foreign key as far as the queries can tell, but the create script fails with the above error. The server is running SQL Server 2005 SP3 (9.00.4035.00).
[Update]: I've just reproduced the issue on a SQL Server 2012 instance. So the version doesn't appear to be too important.
Any idea what could cause this?

It is complaining about the FK constraint that you are trying to add because there is existing data in the table that would no longer be valid if the constraint was successfully applied.
Probably means there is one or more ChangeRequestForecast records where CostingCenterID has a value that doesn't correspond with CostingCenter.CostingCenterID.

Open up SSMS, go to that database, expand that table, and look in the Constraints section. There likely is one in there called "FK_tblChangeRequestForecast_tblCostingCenter" that you need to figure out if you need, and if not, delete it.

Related

Remove record from sys.objects?

I ran a ALTER SCHEMA ... on a table (SQL Server 2012 SP1) but the sys.objects record is still there. When I run the ETL I get an error that the table doesn't exist anymore because it's trying to remove all constraints. This one is of type PK Primary Key Constraint. How can I safely remove the record from the sys.objects table?
I managed to fix this issue by scripting the database to a new one, ALTER SCHEMA ... again on that table to bring it back to dbo., then DROP and recreate the table in the different table schema.

Unable to copy data to SQL server - "There is already an object named in the database."

I've got a table in a legacy non-sql program that has a routine to copy the data into a SQL Server database. The developer of this system wrote the routine with no documentation to see what is happening under the hood. One table I attempted to move ended up failing, now when I try to copy this table over I get the following error:
Unable to create table 'CR_Receipt_Payment_Details'
42S01: [Microsoft][ODBC SQL Server Driver][SQL Server] There is
already an object named 'byReceipt_RECPMT' in the database.
I know that I need to delete this object so that the process can run. I tried running
Drop Table byReceipt_RECPMT
and have the following output:
Cannot use DROP TABLE with 'byReceipt_RECPMT' because 'byReceipt_RECPMT' is a constraint. Use ALTER TABLE DROP CONSTRAINT.
I'm not sure where to go from here.
Can someone point me in the direction of how to find and drop this object?
Thanks.
If the table already exists, then you want to do this:
ALTER TABLE CR_Receipt_Payment_Details DROP CONSTRAINT byReceipt_RECPMT
However, the problem may be that there is a constraint with that name on a DIFFERENT table. You need to find out what table that is. Or else, rename the constraint for THIS table.
This means that your database has a constraint (primary key, foreign key, check, etc.) named byReceipt_RECPMT. Because that name is being used by a constraint, it can't be used by a table.
You could drop the constraint, but so far the only reason you have is that you want to use its name for a table. That's not good enough. If you investigate the constraint and find that it's incorrect or that you don't need it, by all means drop it - Ross Presser's answer shows how to do so.
If you do need the constraint, either rename the constraint or use a different table name. To rename a constraint, use the sp_rename system stored procedure:
sp_rename 'CR_Receipt_Payment_Details.byReceipt_RECPMT', 'new constraint name'
sp_rename documentation (There are examples in the section titled "Renaming constraints").

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

How do you identify a foreign key constraint from its name?

Using Hibernate ORM against SQL Server 11 on ColdFusion 10.
I'm getting the error:
[Macromedia][SQLServer JDBC Driver][SQLServer]The ALTER TABLE
statement conflicted with the FOREIGN KEY constraint
"FK9E8E5409B9A80FE4". The conflict occurred in database "dbname", table
"dbo.TableName", column 'TableId'.
Which seems self-explanatory, except I have checked the relevant table in SQL Server Management Studio and don't find a foreign key constraint with that ID for that table, nor any related tables.
Is there a way to locate the constraint, e.g. by querying the database system tables?
Update: I was looking in the wrong system views - looking inside dbname.sys.foreign_keys I do see a bunch of foreign keys, but checking for the one mentioned in the error returns nothing. Is that the right place to look?
Take a look at the sys.all_objects view, it's easier to query
select
sa.name as FKName
,so.name as TableName
from
sys.all_objects sa
inner join sys.objects so on sa.parent_object_id = so.[object_id]
where
sa.[type] = 'F'

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint

I get the following message even when the table that references it is empty: "Cannot truncate table 'dbo.Link' because it is being referenced by a FOREIGN KEY constraint" Doesn't seem to make much sense why this is occurring. Any suggestions?
In SQL Server a table referenced by a FK cannot currently be truncated even if all referencing tables are empty or the foreign keys are disabled.
You need to use DELETE (may require much more logging) or drop the relationship(s) prior to using TRUNCATE and recreate them afterwards or see the workarounds on this connect item for a way of achieving this using ALTER TABLE ... SWITCH
You cannot truncate a table which has an FK constraint on it. As workaround, you could:
1/ Drop the constraints
2/ Trunc the table
3/ Recreate the constraints.
Here it is the associated T-SQL script, supposing you have 2 tables called MyTable and MyReferencedTable:
-- Remove constraint
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_MyReferencedTable_MyTable')
BEGIN
ALTER TABLE dbo.MyReferencedTable
DROP CONSTRAINT FK_MyReferencedTable_MyTable
END
-- Truncate table
TRUNCATE TABLE dbo.MyTable
-- Re-Add constraint
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_MyReferencedTable_MyTable')
BEGIN
ALTER TABLE dbo.MyReferencedTable
WITH CHECK ADD CONSTRAINT [FK_MyReferencedTable_MyTable] FOREIGN KEY(ListingKey)
REFERENCES dbo.MyTable (ListingKey)
END
Execute the following query to search any constraint:
use MyDatabase
select c.name as c_name, t.name as t_name
from sys.key_constraints c
join sys.tables t on t.object_id = c.parent_object_id
If any constraint found on your table, remove it.
If you are receiving this error and you need to truncate the table then alternative solution could be that you can drop and re-create the table along with primary/other_keys/indexes/triggers. Please make sure that you don't need to the data in that table.
This soulution is working like a charm for me and hardly took a minute to finish. I am doing it for masking purpose.
Not for SQL Server but MySQL only.
Instead of deleting or recreating the constraint, I prefer this simpler way.
Disable the constraint validation by executing the following query first :
SET FOREIGN_KEY_CHECKS=0;
Then truncate your tables
And finally, reactivate the constraint validation :
SET FOREIGN_KEY_CHECKS=1;
Thats a common solution when you migrate databases, so you don't have to worry about the order the tables are inserted in.

Resources