gpt4 book ai didi

c# - 如何更新 SQL 表逻辑

转载 作者:行者123 更新时间:2023-11-30 22:17:51 25 4
gpt4 key购买 nike

我有一个结构如下的表,

Table 3

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

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

更新 Crate ID of 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));
}

最佳答案

您可以在 SQL Server 中使用 MERGE 语法执行“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)

关于c# - 如何更新 SQL 表逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16539315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com