- Remove From My Forums
-
Question
Answers
-
Hi
Try code below to check Constraint:
SELECT OBJECT_NAME(OBJECT_ID) AS
Name_of_Constraint
, SCHEMA_NAME(schema_id) AS SchemaName, OBJECT_NAME(parent_object_id) AS TableNameX, type_desc AS ConstraintType FROM sys.objects WHERE type_desc LIKE '%CONSTRAINT' and OBJECT_NAME(parent_object_id)='yourTable'To DROP:
ALTER TABLE
yourTable
DROP CONSTRAINT <Name_of_Constraint>then
DROP TABLE <yourtable>
Regards, Ryan Lambatan
Please «Mark as Answer» or «Vote as Helpful»-
Edited by
Saturday, September 10, 2011 2:18 PM
-
Marked as answer by
Harry SQL DBA
Monday, September 12, 2011 1:21 AM
-
Edited by
On Transact SQL language the Msg 3726 Level 16 — Could not drop object because it is referenced by a FOREIGN KEY constraint.
Msg 3726 Level 16 Example:
Create tables
USE model;
GO
create table Test_1
(id int not null primary key,
name varchar(500) not null);
GO
create table Test_2
(id int not null primary key,
name varchar(500) not null,
constraint FK_TestID
foreign key (id) references Test_1(id));
GO
Invalid statement:
USE model;
GO
DROP TABLE Test_1;
GO
Message |
---|
Msg 3726, Level 16, State 1, Line 3 |
Could not drop object ‘Test_1’ because it is referenced by a FOREIGN KEY constraint. |
Correct statement:
USE model;
GO
DROP TABLE Test_2;
GO
DROP TABLE Test_1;
GO
Other error messages:
- Is not a constraint
- Create View or Function failed because no column name was specified
- Cannot define PRIMARY KEY constraint on nullable column in table
- Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
- String or binary data would be truncated
- The database name component of the object qualifier must be the name of the current database
- No item by the name of ‘%’ could be found in the current database.
Even though I am removing and trying to drop table, I get error,
ALTER TABLE [dbo].[Table1] DROP CONSTRAINT [FK_Table1_Table2]
GO
DROP TABLE [dbo].[Table1]
GO
Error
Msg 3726, Level 16, State 1, Line 2 Could not drop object ‘dbo.Table1’
because it is referenced by a FOREIGN KEY constraint.
Using SQL Server 2012
I generated the script using sql server 2012, so did sQL server gave me wrong script ?
asked Aug 12, 2014 at 14:54
MathematicsMathematics
7,35425 gold badges78 silver badges152 bronze badges
2
Not sure if I understood correctly what you are trying to do, most likely Table1 is referenced as a FK in another table.
If you do:
EXEC sp_fkeys 'Table1'
(this was taken from How can I list all foreign keys referencing a given table in SQL Server?)
This will give you all the tables where ‘Table1’ primary key is a FK.
Deleting the constraints that exist inside a table its not a necessary step in order to drop the table itself. Deleting every possible FK’s that reference ‘Table1’ is.
As for the the second part of your question, the SQL Server automatic scripts are blind in many ways. Most likely the table that is preventing you to delete Table1, is being dropped below or not changed by the script at all. RedGate has a few tools that help with those cascading deletes (normally when you are trying to drop a bunch of tables), but its not bulletproof and its quite pricey. http://www.red-gate.com/products/sql-development/sql-toolbelt/
answered Aug 12, 2014 at 15:13
Firstly, you need to drop your FK.
I can recommend you take a look in this stack overflow post, is very interesting. It is called: SQL DROP TABLE foreign key constraint
There are a good explanation about how to do this process.
I will quote a response:
…..Will not drop your table if there are indeed foreign keys referencing it.
To get all foreign key relationships referencing your table, you could use this SQL (if you’re on SQL Server 2005 and up):
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')
SELECT
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) +
'.[' + OBJECT_NAME(parent_object_id) +
'] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')
answered Aug 12, 2014 at 15:07
Orlando HerreraOrlando Herrera
3,4811 gold badge34 silver badges44 bronze badges
You need to drop the FK on Table it has been added to, now this can be Table2, Table3 or whatever table, which references Table1’s column as Foreign Key. Then you can drop Table1.
TylerH
20.8k66 gold badges76 silver badges101 bronze badges
answered Aug 12, 2014 at 14:55
Tab AllemanTab Alleman
31.5k7 gold badges36 silver badges52 bronze badges
1
You can use those queries to find all FK in your table and Find the FKs in the tables in which your table is used.
Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'
-- Find FK in This table.
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
answered Oct 29, 2015 at 23:04
Ardalan ShahgholiArdalan Shahgholi
12k21 gold badges108 silver badges144 bronze badges
This happens because the table you are trying to alter has a primary key(PK) which is referenced as a foreign key(FK) somewhere in a different table.To know which table is it, execute the below stored procedure:
EXEC sp_fkeys 'Table_Name'
and then run the drop command which is as follows:
DROP TABLE Table_Name
Note: ‘dbo.’ is a default system derived schema, therefore you need not have to mention that in the command as follows.Don’t worry even if you mention the schema it’ll work.
DROP TABLE dbo.Table_Name
answered May 10, 2018 at 12:58
Tahir77667Tahir77667
2,29020 silver badges16 bronze badges
Using…
Microsoft SQL Server Management Studio (v. 18.11.1)
If you try to just drop the problem table, you’ll get this error:
For being able to drop this table, as suggested by @rjso in his answer, run a new query with the following command to get the first hint of where’s the current problem coming from:
EXEC sp_fkeys 'Table1'
/* In this example the problem is in the table "Titular" */
This will tell you where the problem actually is located:
In this example the problem table is Titular
, and the wronged reference points to the table Expediente
, in its row id_persona
. Let’s go there:
Right click on id_persona
:
Then delete the relationship:
This will allow you now to drop the table (in this case, Titular
table).
PS. I forgot to screenshot it when I dropped it in my database. This solution worked.
answered Apr 22, 2022 at 12:57
carloswm85carloswm85
1,42513 silver badges24 bronze badges
-
April 17, 2004 at 9:34 pm
#85179
In the Transaction replication Publication agent is failing with the Error as mentioned below.
Error number: 3726, Could not drop object ‘Tablename’ because it is referenced by a FOREIGN KEY constraint.
Can we fix this error without dropping the table or any other method to fix please let me know.
—sntiwary
-
Nicholas Cain
SSC-Dedicated
Points: 33009
It appears as though the subscriber has a foreign key defined against the table you are attempting to snapshot. As the snapshot drops and then recreates the remote table having the foreign key constraint prevents this from happening.
Go to the subscriber and run a sp_help against the table to see what references it and then drop the constraint, this should allow the snapshot to run without a problem.
-
Rodrigo Acosta
SSC-Insane
Points: 21261
If the table already exists in the subscriber, you shound’t specify the snapshot to drop it.
You can change that in the properties of each article.
If you need to re create the table each time you apply the snapshot, you can use a pre snapshot script to drop the constraint, let the snapshot to drop and re create the table, and with a post script, you can re create the foreign key.
-
sntiwary
Hall of Fame
Points: 3475
thank for reply. So you mean we cannot replicate the tables with foreign key or subscribers cannot have referential integrity. I Checked a KB article which tells:
When applying the snapshot, the schema files are applied in such a way that the child tables are dropped, and then re-created before the parent tables are re-created. So, even if there are foreign key references, tables can be dropped and re-created successfully.
http://support.microsoft.com/default.aspx?scid=kb;en-us;303218&Product=sql2k
-
Nicholas Cain
SSC-Dedicated
Points: 33009
If you have the integrity enforced on the publisher (and you are replicating both tables out and these are the tables involed in the problem you are having) you don’t have to enforce it on the far end.
However if you are using the replicated table on the far end to enforce the integrity on a table that only exists on the subscriber then as Racosta said, use a pre and post snapshot script to drop and recreate the constraint.
-
Rodrigo Acosta
SSC-Insane
Points: 21261
Even if you published all tables wich are involved in the integrity validation, if you specify the snapshot to drop the table before applying the snapshot, it will fail.
You shoudn’t drop the table in the snapshot.
-
sntiwary
Hall of Fame
Points: 3475
Thanks to stacenic & racosta for the help and your clarification!!
From your message what I understood is that if I am replicating both the tables related to Foreign key then I don’t require that foreign key to be exist at the subscriber and that can I do by unchecking the option «Enforce Relationship for Replication» in their tables design ?
other option, if I want to enforce integrity at subscribers end also then I just need to include a pre and post snapshot script to drop and recreate the constraint, do you mean I need to include that in snapshot agents which has 3 steps as mention below, before the first step to drop the constraint and after its last step to recreate the constraint.
Snapshot agent steps:
1.Snapshot Agent startup message.
2.Run agent.
3.Detect nonlogged agent shutdown.
Please let me know if I have misunderstood.
-
Nicholas Cain
SSC-Dedicated
Points: 33009
If you actually go into the properites of the publication, to the Snapshot tab it allows you to specify locations for scripts to execute before and after the snapshot is run, this would allow you to drop and recreate the constraints.
If you are enforcing referential integrity on the publisher, replicating both tables and not making data changes on the tables on the subscriber then you don’t have to Enforce the relationship for replication as by virtue of having the integrity on the publisher side and transactionally replicating the data you will never run into the problem of parent/child relationships not working.
Viewing 8 posts — 1 through 7 (of 7 total)
- Remove From My Forums
-
Question
-
Hello ,
I know above error because of FOREIGN KEY constraint ,
i dont want to remove foreign key at both the end and want source table as it is to destination
what shoul i do…….
Rahul Hundare
Answers
-
You can disable the constrint but that will lead your data integrity issues…but if you want still…
ALTER TABLE tablename NOCHECK CONSTRAINT constraintname
Do not forget to enable the constraint once you completed your delete…
ALTER TABLE tablename WITH CHECK CHECK CONSTRAINT constraintname
Please use Marked as Answer if my post solved your problem and use
Vote As Helpful if a post was useful.-
Proposed as answer by
Saturday, August 31, 2013 3:42 PM
-
Marked as answer by
Sofiya Li
Thursday, September 5, 2013 7:01 AM
-
Proposed as answer by