Hayden
Hayden

Reputation: 301

Problems with SQL delete statement

I'm getting an error stating that I need a second argument in my remove command, but I believe I already have two in here. I'm pretty new to SQL and C# so maybe I'm not understanding it correctly.

private void RemoveFromRecipeButton_Click(object sender, EventArgs e)
{
    string query = "DELETE FROM RecipeIngredient WHERE Id = @RecipeId & @IngredientId";

    using (connection = new SqlConnection(connectionstring))
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        connection.Open();

        command.Parameters.Remove("@RecipeId", ListRecipes.SelectedValue);
        command.Parameters.Remove("@IngredientId", ListAllIngredients.SelectedValue);

        command.ExecuteScalar();
    }

    PopulateRecipes();
}

I'm thinking it might be because I put both RecipeID and IngredientID in the same line with an &, but that works on my add statement.

So I'm really unsure of how remove should work. Can anyone assist in identifying the issue?

Upvotes: 0

Views: 102

Answers (2)

Cam Bruce
Cam Bruce

Reputation: 5689

There are a few different problems here.

The first one is I'm not sure what your sql is trying to do. Are you actually trying to perform a bitwise AND, or are you just trying to see if Id is equal to both the @RecipeId and @IngredientID?

Additionally, just because your SQL statement has parameters in it, doesn't mean you can use cmd.Parameters.Remove() to remove them. The Command.Parameters collection is used to associate values in your program to specific parameters in your sql statement. You will have to remove the parameters from the literal sql string, if you are truly looking to remove them from the statement.

Upvotes: 0

Blorgbeard
Blorgbeard

Reputation: 103447

You are calling Parameters.Remove when it looks like you want to be calling Parameters.AddWithValue. You're executing a delete statement, but that doesn't mean you want to remove parameters. You still need to add the parameters that specifies what to delete.

Your actual SQL statement is suspect as well - you're currently deleting rows where the bitwise AND of your two parameters matches the Id of the row. Is that what you want?

Upvotes: 2

Related Questions