I have employees attendance table from date 1 to 31 with column names like 1, 2, 3, 4 5…..31
and datatype is nVarchar(5)
I am adding values in those columns (P, H, A) for example:
P = Present
A = Absence
H = Holiday
Now i want to calculate Total (P=Present) in last column that is [TotalPresnets] of Employee.
How to calculate (Count) the string values.
Because you made 31 columns, every type of manipulation will involve fetching all 31 of those columns. This is one of a million reasons why this design is going to cause you a lot of pain. So, I have to say you need to consider changing this design!
If you must stick with this, you will end up with code something like this:
Another ugly solution would be to use dynamic SQL to generate the query above.
In general, when you are forced into such ugly solutions, it’s a good indication that you are approaching the problem wrong.
Note also that this is some 40 lines of code for a very basic operation on a single row. Carrying this technique into the rest of your application is going to cause far more headaches. Imagine if you had to change any logic in here; what should be one line is now 31.
A better design would yield more intuitive / maintainable / readable code: