从多个表中删除ASP.NET

时间:2009-04-28 06:35:28

标签: asp.net sql vb.net ado.net

如何在ASP.Net中使用相同的删除语句一次从两个表中删除?

3 个答案:

答案 0 :(得分:3)

只需连接删除sql脚本:

Using connection As New SqlConnection(connectionString)
    Dim command As New 
       SqlCommand("DELETE FROM Table1 WHERE ID1=@ID1; DELETE FROM Table2 WHERE ID2=@ID2;", connection)

    command.Parameters.Add("@ID1", 1);
    command.Parameters.Add("@ID2", 2);

    command.Connection.Open()
    command.ExecuteNonQuery()
End Using

答案 1 :(得分:1)

我不确定您的意思,但如果您想使用其他表的数据从表中删除,可以使用以下代码段(SQL Server)完成此操作:

DELETE x
FROM TableX x INNER JOIN TableY y
   ON x.SomeID = y.SomeID
WHERE ...

如果要在一个命令中执行两个DELETE语句,可以将它们连接起来,用分号分隔它们:

DELETE TableX WHERE SomeID = ...; DELETE TableY WHERE SomeID = ...

您还可以使用存储过程:

CREATE PROCEDURE DeleteTwoTables
   @ParamX int,
   @ParamY int
AS
   DELETE TableX WHERE SomeID = @ParamX
   DELETE TableY WHERE SomeID = @ParamY

答案 2 :(得分:0)

如果您的数据库是MsSql,您可以在一个SqlCommand中组合多个delete语句。

试试这个:

string deleteQuery = "DELETE FROM Table1; DELETE FROM Table2;";
using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlCommand deleteCommand = new SqlCommand(deleteQuery, connection))
{
    connection.Open();
    deleteCommand.ExecuteNonQuery();
}

这将一次性删除table1和table2中的所有记录。