【问题标题】:How to remove an element from a table that is the result of the intersection of two other tables如何从表中删除作为其他两个表相交结果的元素
【发布时间】:2020-06-30 17:32:48
【问题描述】:

美好的一天!我正在使用 SQL 做一个小型 WPF 程序。我有一个表 Zoo、表 Animal 和 ZooAnimal,它是其他 2 个表的组合。所以这个想法是,通过点击 Zoo 应该是关于位于特定 Zoo + 一些其他功能的动物的信息。

我在实现“移除动物”按钮时遇到了问题。它应该从 ZooAnimal 表中删除选定的动物,但我不知道必须使用什么 SQL 代码来执行此操作。

我试过这样:

private void removeAnimal_Click(object sender, RoutedEventArgs e)
    {
            string query = "delete AnimalZoo Set ZooId = @ZooId where AnimalId = @AnimalId";
            SqlCommand command = new SqlCommand(query, connection);

            connection.Open();
            command.Parameters.AddWithValue("@ZooId", listZoos.SelectedValue);
            command.Parameters.AddWithValue("@AnimalId", listAssociatedAnimals.SelectedValue);
            command.ExecuteScalar();

            connection.Close();
            showAssociatedAnimals();
    }

我很乐意在这方面得到任何帮助。

以下是 WPF UI 的外观:

数据库如下:

ZooAnimal 表定义:

CREATE TABLE [dbo].[ZooAnimal] (
[Id]       INT IDENTITY (1, 1) NOT NULL,
[ZooId]    INT NOT NULL,
[AnimalId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [AnimalFK] FOREIGN KEY ([AnimalId]) REFERENCES [dbo].[Animal] ([Id]) ON DELETE CASCADE,
CONSTRAINT [ZooFK] FOREIGN KEY ([ZooId]) REFERENCES [dbo].[Zoo] ([Id]) ON DELETE CASCADE

);

【问题讨论】:

    标签: c# sql sql-server wpf winforms


    【解决方案1】:
    delete AnimalZoo where AnimalId = @AnimalId and ZooId = @ZooId
    

    【讨论】:

      【解决方案2】:

      此外,在您的 c# 代码中,您调用 ExecuteScalar 来执行 Delete 语句。 此 SQL 使用不提供要返回的字段(它不是查询),因此您最好使用 ExecuteNonQuery。

      command.ExecuteNonQuery();
      

      享受吧!

      【讨论】:

        【解决方案3】:
        string query = "delete from ZooAnimal where AnimalId = @AnimalId and ZooId = @ZooId";
        

        【讨论】:

          猜你喜欢
          • 2021-03-17
          • 2020-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-05
          • 2022-10-01
          相关资源
          最近更新 更多