Given a function Q(c_1, c_2, ..., c_m) that returns an SQL query string of the form "SELECT v_1, v_2, ..., v_n FROM V WHERE v_1='c_1' ..." how will you optimize your code assuming that some c_i's are null?
SOME MATHEMATICS TO CONSIDER
Suppose (m-1) variables are null, then we have Choose(m,1) cases to consider. If there are (m-2) null variables, we have Choose(m,2) cases to consider. If there are (m-3) variables which are null, we have Choose(m,3). If we are to consider all possible cases, we have Choose(m,1) + Choose(m,2) + ... + Choose(m,m). Wow, that is a lot of cases! Add to the fact that some typo error might creep in also! How in the world are you going to optimize?
ANSWER
Generalized VB Code:
Public Function Q(ByVal c_1 As String, _
ByVal c_2 As String, _
..., _
ByVal c_m As String) As String
Dim where_and As String = " WHERE "
Dim sb As New StringBuilder
sb.Append(" SELECT v_1, v_2, ..., v_n FROM V ")
If c_1 <> "" Then
sb.Append(where_and & " v_1='" & c_1 & "' ")
where_and = " AND "
End If
If c_2 <> "" Then
sb.Append(where_and & " v_2='" & c_2 & "' ")
where_and = " AND "
End If
' iterate till c_(m-1)
If c_m <> "" Then
sb.Append(where_and & " v_n='" & c_m & "' ")
End If
Return sb.ToString
End Function
Generalized Java Code:
public String Q(String c_1, String c_2, ..., String c_m) {
String where_and = " WHERE ";
StringBuilder sb = new StringBuilder();
sb.append(" SELECT v_1, v_2, ..., v_n FROM V ");
if (c_1 != null) {
sb.Append(where_and & " v_1='" & c_1 & "' ")
where_and = " AND "
}
if (c_2 != null) {
sb.Append(where_and & " v_2='" & c_2 & "' ");
where_and = " AND ";
}
// iterate till c_(m-1)
if (c_m != null) {
sb.Append(where_and & " v_n='" & c_m& "' ");
}
return sb.toString();
}
No comments:
Post a Comment