I need to choose one of three values of an integer using the value of a column on a nullable column of a table.
There are at least two approaches: 1) use SQL to do all the work: test null values, and choose between the other values, or 2) read the value and use code -in this case Java- to choose.
Which one is "better", ie. easier to understand & more maintainable? Do you have any other metric use to decide?
As an example, I have the following code:
// If id is equal to:
// -1, then make v = 1
// null, then make v = 2
// in any other case, make v = 3
// Option 1:
int v;
String query = "SELECT CASE min(Id) WHEN NULL THEN 2 WHEN -1 THEN 1 ELSE 3 END AS Id"
+ "FROM TableA WHERE SomeField IN (SELECT ...blah blah...)";
ResultSet rs = // execute query
if (rs.next()) {
v = rs.getInt("Id");
} else {
// TODO something went *very* wrong...
}
// Option 2:
int v;
String query = "SELECT CASE min(Id) Id"
+ "FROM TableA WHERE SomeField IN (SELECT ...blah blah...)";
ResultSet rs = // execute query
if (rs.next()) {
final int id = rs.getInt("Id");
if (rs.wasNull()) {
v = 2;
} else if (id == -1) {
v = 1;
} else {
v = 3;
}
} else {
// TODO something went *very* wrong...
}