I’ve written a program in VB.NET in conjunction with a SQL server database table to record the assessment marks of students. The SQL table (Marks) details columns, which show Student_ID, Assessment (e.g. Maths, Science, English) and Mark. The subroutine shown below is designed to allow users to delete specific assessments and, by using the DELETE statement nested within a conditional if/elseif clause, I have managed to achieve this, the program runs fine. However, as a relative newcomer to programming I am conscious about adopting good practice and, if possible, avoiding repetitive code which, in my mind, is clearly evident within the if/elseif clause. This problem becomes increasingly relevant when considering the possibility of having to deal with 15 or more student assessments. My question is, can the SQL query statement be modified to incorporate an ‘assessment’ variable rather than explicitly typing in each condition within an if/elseif clause? I tried to do this in the same way as the variable ‘id’ is used to identify the ‘Student_ID’ within the SQL query statement, but this returned an error stating that, for example, Maths is not a column. Hope I have explained this sufficiently and everything makes sense. Any ideas, as always, most appreciated.
Thanks, Mike
Console.WriteLine("")
Console.Write("Enter assessment to be deleted : ")
Dim assessment_name As String = Console.ReadLine
If assessment_name = "Maths" Then
query = ("DELETE FROM Marks WHERE Assessment='Maths' AND Student_ID=" & id)
ElseIf assessment_name = "English" Then
query = ("DELETE FROM Marks WHERE Assessment='English' AND Student_ID=" & id)
ElseIf assessment_name = "Science" Then
query = ("DELETE FROM Marks WHERE Assessment='Science' AND Student_ID=" & id)
ElseIf assessment_name = "Art" Then
query = ("DELETE FROM Marks WHERE Assessment='Art' AND Student_ID=" & id)
End If
command = New SqlCommand(query, connection)
command.ExecuteNonQuery()
UsingWHEREclause can be refactored toWHERE Assessment=@Assessment AND Student_ID=@Id;. That would allow you to use a single query in addition to the other benefits of parameterized queries.