Execute 2 querys or more

Asked

Viewed 459 times

3

I wanted to execute 2 darlings in C# when the button is clicked, but I can only execute one.

public static void excluireventos()
{
    string connectionString = Conn.tank();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        string query = string.Format("TRUNCATE TABLE Active" + "TRUNCATE TABLE Active_Number");
        using (SqlCommand cmd = new SqlCommand(query,connection))
        {
            cmd.ExecuteNonQuery();
            Globals.UpdateLogs("Todos os eventos foram excluidos com exito!");
        }
    }
}

Both darlings sane TRUNCATE, if I put one will usually more if I put two of the bug in the program and close.

How can I execute 2 darlings or more?

1 answer

2


You are running only one query even, you can run more than one command on it, as long as they are separated with semicolon:

public static void excluireventos() {
     using var connection = new SqlConnection(Conn.tank());
     connection.Open();
     using var cmd = new SqlCommand("TRUNCATE TABLE Active; TRUNCATE TABLE Active_Number", connection);
     cmd.ExecuteNonQuery();
     Globals.UpdateLogs("Todos os eventos foram excluidos com exito!");
}

I put in the Github for future reference.

I simplified the code.

  • Thank you worked perfectly :)

  • I just wanted to add that, as you did, if the first SQL command gives any error (foreign key conflicts, for example), the second command will still be executed, as if nothing had happened. I’ve had some problems because of it and since then I started to use the class Sqltransaction.

  • @Vítormartins well observed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.