简体   繁体   English

INSERT语句与FOREIGN KEY冲突

[英]The INSERT statement conflicted with the FOREIGN KEY

I get this error from SQL Server: 我从SQL Server得到此错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK". INSERT语句与FOREIGN KEY约束“FK”冲突。 The conflict occurred in database "DATABASENAME", table "TABLE", column 'UserID'. 冲突发生在数据库“DATABASENAME”,表“TABLE”,列“UserID”中。 The statement has been terminated. 该语句已终止。

This came from Visual Studio 2008: 这来自Visual Studio 2008:

Unable to cast object of type 'System.Object' to type 'System.IConvertible'. 无法将类型为“System.Object”的对象强制转换为“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# 这来自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 . 当我在这种情况下在网页上添加数据时,我指的是用户,从我获得正确的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. 所以在TABLE中我当然添加了UserID ,但是当我使存储过程工作时,会出现第一条消息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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