小编典典

我如何更新SQL表逻辑

sql

我有一个表的结构为

Table 3

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

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

**表中已经Crate ID 存在 Fruit ID if的 更新Fruit 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));        
}

阅读 152

收藏
2021-04-14

共1个答案

小编典典

您可以使用MERGESQL Server中的语法执行“ upsert”操作:

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)
2021-04-14