I would like to know what performs faster and its preferable a condition in a tsql query like this:
select case 'color' when 'red' then 1 when 'blue' then 2 else 3 end
or performing the same switch in c# code after getting the value from the db?
switch(color):
{
case "red":
return 1;
case "blue":
return 2;
default:
return 3;
}
To add more data in my specific case we have a sql query that returns 5800+ records in some cases (date filters and so) then we concatenate those results in c# (one txt line per record) and generate a txt.
We have one server that is the sql server + webserver(asp.net) and it takes like 10 or more mins to generate it…So we where thinking about doing all the conditions on the sql side, maybe concatenating the fields as one at the sql level too vs using c# loop with StringBuilder?
Right now the sql takes 1 sec to execute and all the time its taken at the concatening loop, there are 5873 records with 11 fields each
I think you are prematurely optimizing. “Make it work, make it right, then make it fast.”
I know this statement (and others like it) bring about a lot of debate, but I think you should be putting this logic in the layer that is most appropriate, as in, where it has the least duplication, most re-usability, easiest to maintain, etc. If you have a performance problem at that point, you can make actual measurements in your environment with your own loads.
As an example, rather than some naked switch like this (that must be maintained), perhaps this should be in a lookup table in the DB and brought back with a join, or maybe it’s better exposed as a property of some class based upon an enum. These might be better patterns to follow.