OK, this is a pretty simple problem, but I'm curious: what is the best approach in terms of efficiency and style?
I often need to select data in MS SQL, but am looking for a single result. If there is no match in the database, I'd like to return a default value.
Here are a few approaches I take:
Do it in Code
--Regular Select in SQL
SELECT myValue FROM dbo.SomeTable WHERE id = @id
//In Data Access Layer
using (IDataReader reader = cmd.ExecuteReader()) {
if (reader.Read()) {
return Convert.ToInt32(reader["myValue"]);
}else {
return 0; //return a default
}
}
Guarantee a returned value in SQL
--SQL stores in a variable and selects null value if available
declare @myVal int
select @myVal = myValue FROM dbo.SomeTable WHERE id = @id
--return value or a default
select ISNULL(@myVal,0) as myValue
//In Data Access Layer
return Convert.ToInt32(cmd.ExecuteScalar());
Is there a more elegant way to do this? Or a more efficiient way?
If not, which of these would you consider a better practice?