INSERT语句与FOREIGN KEY约束冲突

时间:2015-02-19 11:05:43

标签: c# sql-server

得到这个奇怪的问题,

我有一个用户定义的表:

CREATE TYPE [dbo].[Crates_FruitsType] AS TABLE 
(
    [FruitID] [int] NOT NULL,
    [CrateID] [int] NOT NULL
)

一个存储过程:

CREATE procedure [dbo].[Crates_InsertRelateMultipleFruits]
    (@FruitCrates As Crates_FruitsType READONLY)
AS
BEGIN
    DELETE rc
    FROM Crates_Fruits rc
    WHERE rc.CrateID IN (SELECT DISTINCT tmp.CrateID 
                         FROM @FruitCrates tmp);

    INSERT INTO Crates_Fruits (FruitID, CrateID)
       SELECT 
          tmp.FruitID, tmp.CrateID
       FROM 
          @FruitCrates tmp
       WHERE 
          tmp.FruitID <> '-1';
END

表:

CREATE TABLE [dbo].[Crates_Fruits]
(
    [EchoID] [int] NULL,
    [FruitID] [int] NOT NULL,
    [CrateID] [int] NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Crates_Fruits] WITH CHECK 
  ADD CONSTRAINT [FK_Crates_CrateID] 
  FOREIGN KEY([CrateID]) REFERENCES [dbo].[Crates] ([ID])
GO

ALTER TABLE [dbo].[Crates_Fruits] CHECK CONSTRAINT [FK_Crates_CrateID]
GO

ALTER TABLE [dbo].[Crates_Fruits] WITH CHECK 
  ADD CONSTRAINT [FK_Fruits_FruitID2] 
  FOREIGN KEY([FruitID]) REFERENCES [dbo].[Fruits] ([ID])
GO

ALTER TABLE [dbo].[Crates_Fruits] CHECK CONSTRAINT [FK_Fruits_FruitID2]
GO

这个C#代码:

using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
    connection.Open();

    DataTable DT = new DataTable();
    DT.Columns.Add("FruitID", typeof(int));
    DT.Columns.Add("CrateID", typeof(int));

    if (fruitIDs.Count < 1)
       DT.Rows.Add(crateID, -1);
    else
    {
        for (int i = 0; i < fruitIDs.Count; i++)
            DT.Rows.Add(fruitIDs[i], crateID);
    }

    using (SqlCommand command = new SqlCommand("Crates_InsertRelateMultipleFruits", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        var testingparam = command.Parameters.AddWithValue("@FruitCrates", DT);
        testingparam.SqlDbType = SqlDbType.Structured;

        command.ExecuteNonQuery();
    }
}

错误:

  

System.Data.SqlClient.SqlException(0x80131904):INSERT语句   与FOREIGN KEY约束冲突&#34; FK_Crates_CrateID&#34;。该   数据库&#34; FruitFactory&#34;,table&#34; dbo.Crates&#34;中发生冲突,   栏&#39; ID&#39;。声明已经终止。

它完美无缺,但在我传递数据时会出错

CrateID = 172
FruitID = -1

我期待存储过程,

如果FruitID传递为&#34; -1&#34;然后只删除CrateID为172的所有记录 否则,删除CrateID为172的所有记录并添加新的数据表

1 个答案:

答案 0 :(得分:1)

您已颠倒了列的顺序。您的类型定义为(FruitId,CrateId),但是当没有水果ID时,您的C#代码会首先进入crateID

if (fruitIDs.Count < 1)
   DT.Rows.Add(crateID, -1);

应该是

if (fruitIDs.Count < 1)
   DT.Rows.Add(-1,crate);

要直接执行存储过程,只需使用表类型创建变量并插入所需的值,例如:

declare @t [Crates_FruitsType]
insert into @t VALUES(-1,172)
exec [Crates_InsertRelateMultipleFruits] @t