how can i update SQL table logic

2019-02-26 12:03发布

I have a table structured as,

Table 3

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

Now I need to execute a query which will,

Update Crate ID of Fruit ID if Fruit ID is already in Table, and if not then insert record in table 3 as new record.

This is what I got in code right now,

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));        
}

1条回答
小情绪 Triste *
2楼-- · 2019-02-26 12:32

You can do an "upsert" with the MERGE syntax in SQL Server:

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);

Otherwise, you can use something like:

update [SomeTable] set CrateID = @CrateID where FruitID = @FruitID
if @@rowcount = 0
    insert [SomeTable] (FruitID, CrateID) values (@FruitID, @CrateID)
查看更多
登录 后发表回答