.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 INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblLinks_tblWebSite".

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

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.

View Complete Post

More Related Resource Links

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


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'.

insert statement violated because Foreign key constraint


I  create an SSIS package, i use data flow to import rows from different server to local server. Unfortunately, there always be error message something about insert statement violated because of foreign key "The INSERT statement conflicted with the FOREIGN KEY constraint" since the table is transactional table that has some foreign key. I want to minimize using temporary table and trying to use toolbox item in ssis.I would appreciate any since i am ssis newbie.


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 DELETE statement conflicted with the REFERENCE constraint. The conflict occurred in database.



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.


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

INSERT Statement Inside a UDF?

I am using SQL Server 2005.  I know you can not put INSERT or UPDATE statements in a UDF.  I am looking for an alternative to getting the end result I need since this call has to go at a specific point in the code or it will never work.  I have a UDF which packs smaller boxes into a bigger box efficiently.  The UDF typically runs and creates as many bigger boxes as possible until all smaller boxes are used and then it returns a TABLE variable back to a stored procedure.  I need to insert a record into a new table at the point where each bigger box is full before it moves on to the next bigger box.  There is only a couple alternatives I can see but don't really know if each is possible.  I am open to an ideas: 1. Call a stored procedure from the UDF which executes the insert statement 2. Using EXECUTE to perform the insert statement 3. Re-write the UDF as a stored procedure.  It must be able to table two inputs and return a table which can be unioned with two other views. 4. Anything Else UPDATE: Scratch idea #1 since it says I can only call other functions or extended stored procedures UPDATE: Scratch idea #2 as it did not work

Foreign key constraint not replicating

We have a merge replication setup with one publisher/distributor and several subscribers.  Several of the tables being replicated have foreign key constraints and these replicate without issue.  However, some foreign key constraints that utilize cascading do not replicate.  To make matters worse, some tables with these cascading fk constraints replicate fine while others do not.  Has anyone run across this behavior and is there a fix for it?  The cascades will dramatically reduce our merge conflicts and help maintain the integrity of the data so we need to keep them in place.

INSERT statement with OUTPUT clause, referencing outer query columns

I have a problem to solve and I have run into what appears to be a limitation of TSQL.  I have looked around and did not find much on this subject, so I apologize if this duplicates another post.  I am using SQL Server 2008. From what I have read on BOL, when you are performing a DELETE or UPDATE statement, you can reference unaffected columns from the outer query in the OUTPUT clause, but this is apparently not allowed in an INSERT statement. I am working on a process that will create new copies of existing records - essentially, the user can create a whole new copy of a set of records, and the process requires that I track both what the original PK values were and the corresponding PK values for the new rows. This example will hopefully spell out my problem.  This script shows two tables, [Primary_Object] and [Secondary_Object].  Not shown here are multiple tables that rely on [Secondary_Table], which is why I have to be able to track this info. This first script shows the setup of the tables involved and the data involved: /* create test data */ create table primary_object ( primary_object_id int identity(1,1), parent_object_id int, name char(1)) create table secondary_object ( secondary_object_id int identity, primary_object_id int, amount money) insert into primary_object (parent_object_id, name) select 0, 'A' insert into secon

Insert Into SQL Server inside a For Each - Next Statement

I have the following code to For each Item in the file uploader, Insert Into database.... but It doesnt work in the For Each Statement but if i take it out of the For Each statement it works.   For Each item As AttachmentItem In Attachments1.Items            Dim objConn2 As New SqlConnection("Data Source=XXX")            objConn2.Open()            Dim objCmd2 As New SqlCommand("INSERT INTO clientport (name, event, date1, username, password, path)" & "VALUES (@name, @event, @date1, @username, @password, @path)", objConn2)                                 objCmd2.Parameters.AddWithValue("@name", clientname.Text)            objCmd2.Parameters.AddWithValue("@event", [event].Text)            objCmd2.Parameters.AddWithValue("@date1", [date].Text)            objCmd2.Parameters.AddWithValue("@username", username.Text)  &nbs

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,

Create a sql foreign key constraint

Hi, I wish to create a constraint that state as below Code.CodeTable ( CodeID smallint, CategoryID smallint,....)  --> Parent Table Admin.Document( DocumentTypeID smallint,.....)  --> Child Table The FK will be Admin.Document.DocumentTypeID map with Code.CodeTable.CodeID I wish to have the contraint that only check Code.CodeTable.CodeID which the Code.CodeTable.CategoryID =15 only. Thanks.Meng Chew

Violation of PRIMARY KEY constraint 'PK_User_Details'. Cannot insert duplicate key in object 'dbo

hi,i'm using sql server 2005 as backend for web development .In one of my database table User_Details, 'user_id' is the primary key ,and it is set to autoincrementing as follows.object count = objUser.countUid(); string count1 = Convert.ToString(count);            if (count1 == "0")            {                string uid5 = "U1";           objUser.addUser(string uid5);}else{               object uid = objUser.selectUid();                string usid = uid.ToString();                string uid2 = usid.Substring(1);                int uid3 = int.Parse(uid2);                uid3 += 1;                string uid4 = usid.Substring(0, 1);          

Insert statement giving me syntax error


Good evening,


I have a MS Access table with the "ModelID" column set as AutoNumber and primary key. The ModelID is set as Field Size --> Long Integer, New Values --> Increment, Format --> General Number, Indexed --> Yes (No Duplicates).

Here is the code i am trying to execute, and is giving me an exception -> insert into syntax error:

string strInsert = "INSERT INTO tbl_Models (fName, lName, Image, Answer1, Answer2, Answer3, Answer4, Answer5, Votes, ImageHead, Age, Program, StudentID, PhoneNumber, EMail) VALUES (@fName, @lName, @Image, @Answer1, @Answer2, @Answer3, @Answer4, @Answer5, @Votes, @ImageHead, @Age, @Program, @StudentID, @PhoneNumber, @EMail)";
        OleDbCommand cmdInsert = new OleDbCommand(strInsert, myCon);

        cmdInsert.Parameters.AddWithValue("@fName", txtFirstName.Text.ToString());
        cmdInsert.Parameters.AddWithValue("@lName", txtLastName.Text.ToString());
        cmdInsert.Parameters.AddWithValue("@Image", FileUploadBody.FileName.ToString() + sRandomBody);
        cmdInsert.Parameters.AddWithValue("@Answer1", txtWhyBeAModel.Text.ToString());
        cmdInsert.Parameters.AddWithValue("@Answer2", "");
        cmdInsert.Parameters.AddWithValue("@Answer3", "

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object


i am unable to insert values into my table when i am using primary key and foreign key in my tables i am sure that i have not voilated the constraints rules and its working well when i remove the constraints.....

(INSERT EXEC statement cannot be nested.) and (Cannot use the ROLLBACK statement within an INSERT-EX


hi all
i have a very important issue,

read this scenario please

i have three Stored Procedures Sp1,Sp2 and Sp3 .

the first one (Sp1) will execute the second one (Sp2) and save returned data into @tempTB1 and the Second one will execute the third one (Sp3) and save data into @tempTB2.

if I execute the Sp2 it will works and it will returned me all my data from the Sp3 ,but the problem is in the Sp1, when i execute it it will display this Error:

INSERT EXEC statement cannot be nested

I tried to change the place of execute Sp2 and it display me another error:

Cannot use the ROLLBACK statement within an INSERT-EXEC statement.

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