c# - 如何更新 SQL 表逻辑

标签 c# sql sql-server webforms

我有一个表结构为,

Table 3

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

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

更新 箱子 ID of 水果 ID 如果 水果 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 语法执行“更新插入”:

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/

相关文章:

javax.servlet.jsp.JspException : Unable to get connection, 数据源无效 : "java. sql.SQLException:找不到合适的驱动程序

sql - 在 PostgreSQL 8.4 中记录 SELECT 语句

c# - 使用 EF LazyLoading 初始化属性?

c# - 无法在 EF Core 中使用 FromSql 调用存储过程

c# - 在 C# 中线程化 2 个 Web 服务调用和组合结果数据的最佳方法是什么?

sql - 按 varchar 列排序

sql-server - 在Linux上安装Squirrel sql客户端驱动程序以连接到MS sql服务器

C#,System.Timers.Timer,每分钟与系统时钟同步运行

sql - 条件 update_all 与 ActiveRecord 中的连接表?

sql-server - SQL Server 安全性,新数据库默认为只读