Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Delete Data from Two tables in single query
    primarykey
    data
    text
    <p>I have two tables: <code>Accounts</code>, which contains the information of accounts that a user has, and <code>AccountUsers</code>, which contains the list of users that have accounts in aforementioned <code>Accounts</code> table.</p> <p>If I have to delete a user then I would have to delete them from both tables where as <code>AccountUsers</code> will have one row of that user where as other may have many because a single user can have many accounts.</p> <p>I wrote the following code that works well and deletes the row from both tables, but whenever there are multiple rows in the second table it fails to delete them and <code>ExecuteNonQuery()</code> returns 0, which means 0 rows are affected.</p> <p>I would like to know if it can be done in a single line. Also, how can it be done for multiple rows in the second table, as my existing code only works if there is single row.</p> <p>Code: </p> <pre><code>public static bool DeleteUser(int UserId) { if (ConnectDatabase()) { sql_cmd = new SqlCommand(); sql_cmd.Connection = sql_con; sql_cmd.Parameters.Add("@userId", SqlDbType.Int).Value = UserId; sql_cmd.CommandText = "DELETE FROM AccountsUsers WHERE Id = @userId"; if (sql_cmd.ExecuteNonQuery() == 1) { sql_cmd = new SqlCommand(); sql_cmd.Connection = sql_con; sql_cmd.Parameters.Add("@userId", SqlDbType.Int).Value = UserId; sql_cmd.CommandText = "DELETE FROM Accounts WHERE userId = @userId"; if (sql_cmd.ExecuteNonQuery() == 1) { return true; } else return false; } else return false; } else return false; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload