简体   繁体   中英

The INSERT statement conflicted with the FOREIGN KEY

I get this error from SQL Server:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK". The conflict occurred in database "DATABASENAME", table "TABLE", column 'UserID'. The statement has been terminated.

This came from Visual Studio 2008:

Unable to cast object of type 'System.Object' to type 'System.IConvertible'.

This is what I got

CREATE TABLE DATABASENAME.TABLE 
(
    UserID INT IDENTITY,
    ...
    ...

    CONSTRAINT PK_Users PRIMARY KEY NONCLUSTERED (UserID),
) ON [PRIMARY]
GO

CREATE TABLE DATABASENAME.OTHERTABLE 
(
    ...
    ...
    ManagerUserID INT NOT NULL,
    ...
    CONSTRAINT FK FOREIGN KEY (ManagerUserID) REFERENCES TABLE (UserID)
) ON [PRIMARY]
GO

The stored procedure is:

CREATE PROCEDURE STOREDPROCEDURENAME
(@ManagerUserID int,   
 ...
 ...
)
AS 
    INSERT INTO OTHERTABLE(..., ManagerUserID, ...)
    VALUES (..., @ManagerUserID, ...)

This came form c#

_projectID = Convert.ToInt32(SqlHelper.ExecuteScalar( 
ConfigurationSettings.AppSettings[TimeWeb.Web.Global.CfgKeyConnString],
 "STOREDPROCEDURENAME", ..., ..., _managerID, ...));

When I'm adding data on the webpage in this case I mean about the user, from methods I get the right UserID . But then happens this.

So in TABLE I got the UserID added of course, but in the moment when I'm making the stored procedure working in, the first message appears.

Can't realize what is wrong with my code. Thanks guys.

For Your Store procedure.

try

CREATE PROCEDURE STOREDPROCEDURENAME
(@ManagerUserID int,   
 ...
 ...
)
AS 
Begin
 if exists(select * from DATABASENAME.TABLE where UserID=@ManagerUserID) --check if pk exists to the ref rable
   begin
   INSERT INTO OTHERTABLE(..., ManagerUserID, ...)
     VALUES (..., @ManagerUserID, ...)
   end
End

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM