.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

The DELETE statement conflicted with the REFERENCE constraint. The conflict occurred in database.

Posted By:      Posted Date: October 15, 2010    Points: 0   Category :ASP.Net


I am getting the following error 

The DELETE statement conflicted with the REFERENCE constraint "FK_Person_Country_CountryID_CountryID".
The statement has been terminated.

I know what the problem is, but can anyone help me in catching this exception in the best possible way?

I do not want the user to delete the country if there are any FK contrains. Or a better way will be to ask the user if they want to delete the records referencing this "Country".

int countryID = Convert.ToInt32(gvCountry.DataKeys[e.RowIndex].Value);
        db.DeleteCountry(1, 1, countryID);
        gvCountry.EditIndex = -1;

**i am using linq to sql

Thank you.


View Complete Post

More Related Resource Links

The DELETE statement conflicted with the REFERENCE constraint


I have created ASP.Net Dynamic data web site using scaffolding in Visual Studio 2010. When I click on delete in data grid for customer table I got below error message.

The DELETE statement conflicted with the REFERENCE constraint "FK_Order_Details_Products". The conflict occured in database "../NORTHWIND.MDF", table "dbo.order details", column 'ProductId'

The statement has been terminated


The DELETE statement conflicted with the REFERENCE constraint "FK_tblAdvanceLink_tblLink


I"m using table adapters here. I tried to use the following in my table adapter:

ALTER TABLE tblAdvanceLInk

DROP FOREIGN KEY FK_tblAdvanceLink_tblLink

DELETE FROM [tblAdvanceLink] WHERE WebsiteID=@WebsiteID 


The DELETE statement conflicted with the REFERENCE constraint "FK_tblAdvanceLink_tblLink". The conflict occurred in database "LinkExchanger", table "dbo.tblAdvanceLink", column 'LinkID'.
The statement has been terminated

I get the same problem every time. So I read you could do this in a sql query. Why doesn't this work in my tableadapter? Do I have this in the right place?  Do I also put this into the other table? (tblLInk)

Isn't there a way to just relax ALL constraints so I can delete some rows? I'm deleting rows from both tables which have the corresponding websiteID

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint


The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "fk_Allergy". The conflict occurred in database "MSCPROJECT", table "dbo.Severity", column 'SeverityCode'.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblLinks_tblWebSite".


How does this happen? the tblLinks doesn't even have a column called websiteID.  websiteID is the primary key of the table tblwebsite. LinkID is the primary key of tblLinks. There is not LinkID column in tblwebsite.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblLinks_tblWebSite". The conflict occurred in database "Linkexchanger", table "dbo.tblWebSite", column 'WebSiteID'. The statement has been terminated.


So how does this happen? How do I terminate the foreign key relationship? I understand I can add this to my Insert stored procedure:

DROP CONSTRAINT FK_tblLinks_tblWebSite

but that stored procedure is used for other functions in my website, and I don't know if doing that is a good idea. Is there a way to relax the constraints for the purpose of this function here?  I'm taking data from a backup links table and trying to write a new row in the links table.

INSERT statement conflicted with COLUMN FOREIGN KEY constraint...


Hi there,

I have a stored procedure which i pass a number of parameters into. One of these parameters is staffNo (only passed this in because i couldn't execute the query without it). The thing is this field can be Null, but when trying to pass null into it it comes up with an Foreign Key conflict. staffNo is a foreign key within the table i'm inserting the data into.

This is the error i get:

"INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'PropStaffFK'. The conflict occurred in database 'DewMountain', table 'TblStaff', column 'staffNo'. The statement has been terminated. The 'PropertyAdvert' procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead. "


Does anyone know of away around this? how to pass a null value to the stored procedure without it causing this error.

Thank you


SQL DIAGOSITC MANAGER tools capture "SELECT *" statement while ALTER / ADD CHECK CONSTRAINT is execu

Hello  ,   I exectuted the code(alter/add with check)  below in SSMS . My_table has 200 millions records . While running the alter/add with check query  the server crashed and the “SQL DIAGOSITC MANAGER” which run on the top of sql serever alert the DBA that select * from my_table was obtained from the last command issued by the user using a DBCC command.      Where does the select * from my_table comes from ? I didn’t excuted select * from my_table at all .   After the sql serever re started I was able to run the command below with out any problem. I checked the SQL PROFILER for the trace there is no “select * from my_table” .   So again where this select * from my_table comes from ?   Here is my initial query ----------------------------------------------------------------- ALTER TABLE [Dbo].my_table WITH CHECK ADD  CONSTRAINT [FK_key1] FOREIGN KEY([Key1]) REFERENCES [Dbo].[Dim_table1] ([Key1]) GO   ALTER TABLE [Dbo].my_table CHECK CONSTRAINT [FK_key1] GO   ALTER TABLE [Dbo].my_table WITH CHECK ADD  CONSTRAINT [FK_key2] FOREIGN KEY([key2]) REFERENCES [Dbo].[Dim_table2] ([key2]) GO   ALTER TABLE [Dbo].my_table CHECK CONSTRAINT [FK_key2] GO   ALTER TABLE [Dbo].my_table WITH CHECK ADD  CONSTRAINT [FK_key3] FOREIGN KEY([d], [c], [r], [g]) REFERENCES [Dbo].my

Is this a bug in MERGE statement with DELETE/INSERT?

This looks to me like a bug with MERGE statement. This does not work on SQL 2008 and 2008 R2. Note that the first commneted statement works properly but the second does not. Is there any explanation why not, other than a bug? Duplication script below. use tempdb go /* IF object_id('dbo.Test', 'U') IS NOT NULL DROP TABLE dbo.Test go IF object_id('dbo.Src', 'U') IS NOT NULL DROP TABLE dbo.Src go */ IF object_id('dbo.Test', 'U') IS NULL BEGIN     CREATE TABLE dbo.Test     (         intID int NOT NULL IDENTITY PRIMARY KEY         ,sysID int NOT NULL         ,ioID int NOT NULL         ,Code nvarchar(10) NOT NULL     )     INSERT dbo.test (sysID, ioID, Code) VALUES (1, 1, 'A')       CREATE UNIQUE NONCLUSTERED INDEX [UIXF_Test] ON [dbo].[Test]     (           [sysID] ASC,           [ioID] ASC     )     WHERE ([ioID] IN ((1)))     WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON,

Update Statement help from Multiple database

Hi I am having two separate datbase on same sever one datasbase name private from where i am executing my below query and other name is ODS Table name in Private=[A].[DimCapabilitySpecialty] Table name in ODS = [A].[CapabilitySpecialty]   both of them having column SpecialtyCd   i want to update the flag value of ODS table where there is particular specialitycd missing in source means table in private database   so for that i wrote below query   update A.DimCapabilitySpecialty set ActiveInd ='I' where SpecialtyCd !=[ODS].[A].[CapabilitySpecialty].[SpecialtyCd]   But it is giving me this error   Msg 4104, Level 16, State 1, Line 1 The multi-part identifier "ODS.CapabilitySpecialty.SpecialtyCd" could not be bound.

error '8007202f' Automation error A constraint violation occurred

I have an old COM+ object that we've used to create AD user accounts with information from our HR system.  This process has been broken since a recent upgrade, so I'm attempting to modify the object to point to a new DC and a new inforamtion store during mailbox creation.  After modifying the code I am unable to get an account to be crated and the following error appears: error '8007202f' Automation error A constraint violation occurred I am not a developer and I know that this is a long shot but if anyone has any insight into if this is an AD issue or one with VB 6, any help at all would be greatly appreciated.  I think this is the relevent code but again, I'm an admin not a developer:     thenewuser.SetInfo        thenewuser.SetPassword "NewBie!!!"     thenewuser.AccountDisabled = False        Set objMailbox = thenewuser         objMailbox.CreateMailbox "LDAP://MyDCCN=Mailbox Store (MyExchServer),CN=First Storage Group,CN=InformationStore,CN=MARLEY,CN=Servers,CN=MyStuff,CN=Administrative Groups,CN=MyStuff,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=MyDomain,DC=com"thenewuser.SetInfo Thanks in advance for any help.

How to delete a sqlexpress database from the visual 2005

Hello, I created a database in my local sqlexpress server, using the 'Create New SQL server database ..." option in the Server Explorer of VS 2005. How can i delete this database now using VS 2005 ? it seems that the 'Delete' option, only remove the link in the 'Data Conncetions ' folder. Thanks and Regards Denis

Can't delete database-file

HelloThis has been driving me crazy all day and I've had to shutdown the website so I'm pretty stressed right now.I'm trying to delete ASPNETDB.MDF on a server but I keep getting the error "Cannot delete ASPNETDB: It is being used by another person or program". I've shut down both the website and the SQL Server service but the problem remains.I've also tried detaching it using 'sp_detach_db' but get:"CREATE DATABASE permission denied in database 'master'. An attempt to attach an auto-named database for file ASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened".The server is running Windows Server 2003 and Microsoft SQL Server 2005 Express.Any suggestions?Thanks.

An error occurred within the report server database. This may be due to a connection failure, timeo



I can't get Reporting Services to work with Sharepoint.

I've followed the instructions for installation of Reporting Service in SharePoint Integrated Mode, and completed the indicated steps on the SharePoint Central Administration Site successfully.  When I try to create a page with a Reporting Services Webpart, I get the following error:


Invalid object name 'History'.
An error occurred within the report server database.  This may be due to a connection failure, timeout or low disk condition within the database. (rsReportServerDatabaseError)


I have SQL 2008 R2, SharePoint Enterprise 2010, and Report Builder 3.0.  SQL and Sharepoint are installed on the same server.

I'm certain that there isn't a disk or timeout problem, so I'm assuming that it's a connection failure, but don't know what steps to take to troubleshoot and correct this.


Why single SQL delete statement will cause deadlock?


Hello everyone,

I am using SQL Server 2008 Enterprise. I am wondering why even a single delete statement of this stored procedure will cause deadlock if executed by multiple threads at the same time? Any tools or sample codes which could be used to reproduce this scenario?

For the delete statement, Param1 is a column of table FooTable, Param1 is a foreign key of another table (refers to another primary key clustered index column of the other table). There is no index on Param1 itself for table FooTable. FooTable has another column which is used as clustered primary key, but not Param1 column.

    create PROCEDURE [dbo].[FooProc]   
     @Param1 int
     ,@Param2 int 
     ,@Param3 int 
    DELETE FooTable WHERE  Param1 = @Param1    
    INSERT INTO FooTable   

how to restore the data that i delete from the database


how to restore the data from the database

i deleted some rows from one table

can restore the data??

i didnt use begin tran and rollback

A USE database statement is not allowed in a procedure, function or trigger.




I’m automating a large Archiving\Purging script on 1TB multi-databases.


I run all Sp’s from Archive database (Destination database).


The log file gets full fast in both source and destination databases and the whole process stopped, I have to clear all log files, as well I have to shrink file after clearing it.


INSERT statement and Getting Data From User Into My Database



I have spent 2 days reading and trying to figure this out and everything i have read and every book I have brought only tells how to read info from a database and how to edit info that is in a database and they all display the data in the database!

I have a page created (getinfo.aspx)

On that page I have a correctly configured SQLDatasource (SQLSource1) (it is set to allow insert, edit and delete).

I have 1 fileupload control

I have 2 text boxes

I have 2 drop down list boxes

The 2 drop down list boxes are "binded" to to seperate tables (via 2 other correctly configured SQLDatasource controls 0 but with out permission to insert, edit or delete) and they correctly provide a drop down list for the user to pick from the 51 states and the 200+ Countries. Those work wonderfully).

I also have a Button Control

The table (myFriends) that SQLSource1 is "connected to" has the following columns:
Column Name  Type   Length Nullable
   userID  uniqueidentifier 16 false
   userName  sql_variant  80

Delete a Site Collection without a Content database


I have a site collection whose content database has been deleted with no backup. Now I want to delete the site collection and i get what seems to be a sql login error. I know the account I am using has enough access to the sql server (used this account to install sharepoint). I am guessing it is complaining because it can't find the database.

Remove-SPSite : Cannot open database "WSS_Content_Database" requested by the lo
gin. The login failed.
Login failed for user 'DOMAIN\PowerfulAccount'.
At line:1 char:14
+ Remove-SPSite <<<<  https://sitename.domain.com/mysite/username
    + CategoryInfo          : InvalidData: (Microsoft.Share...mdletRemoveSite:
   SPCmdletRemoveSite) [Remove-SPSite], SqlException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRemoveSi

I used the Remove-SPSite <URL of site to delete> command.

Any ideas?

Thanks, Berney

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend