繁体   English   中英

从2个相关表中删除行

[英]Delete row from 2 related tables

我的数据库(Echipa和Staff)中有2个表与关系连接。 在此输入图像描述

要在我的表中添加一行,我只需添加第一行,然后添加第二行

private void AddElement(string nume, string an, string tara, string antrenor, string presedinte, string actionar)
{
    conexiune.Open();
    Comanda comanda = new Comanda("insert into echipa values( @nume, @an,@tara)", conexiune);
    comanda.Parameters.Add(new SqlParameter("@nume", nume));
    comanda.Parameters.Add(new SqlParameter("@an", an));
    comanda.Parameters.Add(new SqlParameter("@tara", tara));
    comanda.ExecuteNonQuery();


    comanda = new Comanda("insert into staff values( @antrenor,@presedinte,@actionar)", conexiune);
    comanda.Parameters.Add(new SqlParameter("@antrenor", antrenor));
    comanda.Parameters.Add(new SqlParameter("@presedinte", presedinte));
    comanda.Parameters.Add(new SqlParameter("@actionar", actionar));
    comanda.ExecuteNonQuery();

    conexiune.Close();
    MessageBox.Show("Succes");
}

但是,如果我想从两者中删除一行来更新一行呢? 我应该怎么做?

我不知道为什么但我甚至不能从1表中删除

private void DeleteElement(string nume)
{
    conexiune.Open();
    Comanda comanda = new Comanda("delete from echipa where 'nume'=@nume", conexiune);
    comanda.Parameters.Add(new SqlParameter("@nume", nume));

    comanda.ExecuteNonQuery();

    conexiune.Close();
    MessageBox.Show("Succes");
}

这对我的桌子没有任何作用..

最好的方法是在两个表之间的外键上设置级联删除。 这样,当您从主表中删除行时,第二个表中的所有子行都将被自动删除。

尝试这个。 在“echipa”之后定义列。

conexiune.Open();
    Comanda comanda = new Comanda("insert into echipa(nume, an, tara) values( @nume, @an,@tara)", conexiune);
    comanda.Parameters.Add(new SqlParameter("@nume", nume));
    comanda.Parameters.Add(new SqlParameter("@an", an));
    comanda.Parameters.Add(new SqlParameter("@tara", tara));
    comanda.ExecuteNonQuery();

我找到了解决方案。

我有2个表Echipa - 有EID(int)作为主键和autonumber Staff - 有SID(int)只是自动编号

首先,我必须删除工作人员的行,然后从Echipa删除它,它的工作原理! 在某个地方,我使用Comanda = System.Data.SqlClient.SqlCommand,对我来说更容易)并且是我的语言)

 private void StergeElement(string nume)
    {
        conexiune.Open();


        Comanda comanda = new Comanda("delete from staff where SID=@ID", conexiune);
        comanda.Parameters.Add(new SqlParameter("@ID", nume));

        comanda.ExecuteNonQuery();

         comanda = new Comanda("delete from echipa where EID=@ID", conexiune);
        comanda.Parameters.Add(new SqlParameter("@ID", nume));

        comanda.ExecuteNonQuery();



        conexiune.Close();
        MessageBox.Show("Succes");
    }

感谢@apomene的答案,它对我有所帮助!

如果已取得不删除,(我猜你的字段名是nume ),你只需要去掉引号:

Comanda comanda = new Comanda("delete from echipa where nume=@nume", conexiune);
        comanda.Parameters.Add(new SqlParameter("@nume", nume));

        comanda.ExecuteNonQuery();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM