繁体   English   中英

从数据库删除时出错

[英]error while deleting from database

我有2个表MachineGroups和Machines。

机器组具有以下值:

机器组ID
MachineGroupName
机器集团

机器具有以下价值:

MachineGroupID(FK)
机器ID
机器名称Machinedesc

现在,我想删除计算机组,但是它给了我一个错误,因为其中已经有值。

因此,我想删除其中没有计算机的那些值,如果在特定计算机组中预设了计算机,则会给出错误消息。

我尝试用查询工作,但它不起作用..

 System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString =
                @"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;
            long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]); 
            //tell the compiler and database that we're using parameters (thus the @first, @last, @nick)  
            **dataCommand.CommandText = ("Delete from [MachineGroups] where  [MachineGroupID]=@MachineGroupID not in ( select distinct MachineGroupId  from Machines )");**

            //add our parameters to our command object  
            dataCommand.Parameters.AddWithValue("@MachineGroupName", MachineGroupName);
            dataCommand.Parameters.AddWithValue("@MachineGroupDesc", MachineGroupDesc);
            dataCommand.Parameters.AddWithValue("@TimeAdded", TimeAdded);
            dataCommand.Parameters.AddWithValue("@MachineGroupID", MachineGroupID);
            dataConnection.Open();

            dataCommand.ExecuteNonQuery();
            dataConnection.Close();

在这里我试图删除特定的machineGroup ...

如果还有其他方法,请提出建议。

Delete from MachineGroups 
where MachineGroupId not in 
    (select distinct MachineGroupId  from Machines);

我没有尝试过这一部分,但它应该给您一个想法

Delete from MachineGroups 
WHERE NOT EXISTS ( SELECT TOP 1 MachineID FROM Machines 
WHERE Machines.MachineGroupID= MachineGroups.MachineGroupID )

暂无
暂无

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

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