如何更新SQL表逻辑

本文关键字:SQL 更新 何更新 | 更新日期: 2023-09-27 18:13:20

我有一个结构为的表

Table 3
Fruit ID -  Foreign Key  (Primary Key of Table 1)
Crate ID -  Foreign Key  (Primary Key of Table 2)

现在我需要执行一个查询,

如果Fruit ID已在表中,则更新Fruit IDCrate ID,如果不在,则将记录作为新记录插入表3中

这就是我现在的代码,

private void RelateFuirtWithCrates(List<string> selectedFruitIDs, int selectedCrateID)
{
   string insertStatement = "INSERT INTO Fruit_Crate(FruitID, CrateID) Values " +
        "(@FruitID, @CrateID);";  ?? I don't think if it's right query
        using (SqlConnection connection = new SqlConnection(ConnectionString()))
        using (SqlCommand cmd = new SqlCommand(insertStatement, connection))
        {
            connection.Open();
            cmd.Parameters.Add(new SqlParameter("@FruitID", ????? Not sure what goes in here));
            cmd.Parameters.Add(new SqlParameter("@CrateID",selectedCrateID));        
}

如何更新SQL表逻辑

您可以在SQLServer:中使用MERGE语法进行"upstart">

MERGE [SomeTable] AS target
USING (SELECT @FruitID, @CrateID) AS source (FruitID, CrateID)
ON (target.FruitID = source.FruitID)
WHEN MATCHED THEN 
    UPDATE SET CrateID = source.CrateID
WHEN NOT MATCHED THEN   
    INSERT (FruitID, CrateID)
    VALUES (source.FruitID, source.CrateID);

否则,您可以使用以下内容:

update [SomeTable] set CrateID = @CrateID where FruitID = @FruitID
if @@rowcount = 0
    insert [SomeTable] (FruitID, CrateID) values (@FruitID, @CrateID)