views:

174

answers:

3
+4  Q: 

Simplify this code

I hate code that looks like its been hacked together. I have just written this:

update table1.dbo.totals
    set @FEE = case
       when isnull(g.SGROUPS,0) > 1
         then @GROUPPRICE * case
             when CHARINDEX('JMCG', g.GROUPS) > 0
                 then (g.SGROUPS - 2)
                 else (g.SGROUPS - 1)
                 end
             else      0
          end   
from @GROUPMEM as g

if @FEE < 0
begin
    set @GROUPFEE = 0
end

I'm particularly wanting to get rid of that nested CASE. Any suggestions?

+3  A: 

Ok so this a little odd but may be cool. It gets rid of your nested case and uses some bitwise operations...

update table1.dbo.totals
    set @FEE = COALESCE((g.SGROUPS^1)&1,0) * @GROUPPRICE * 
          case
             when CHARINDEX('JMCG', g.GROUPS) > 0 then (g.SGROUPS - 2)
             else (g.SGROUPS - 1)
          end
from @GROUPMEM as g

if @FEE < 0
begin
    set @GROUPFEE = 0
end

You're probably asking what (g.SGROUPS^1)&1 does... This basically converts g.SGROUPS to one if it has a value, allowing us to use it in the multiplication.

Abe Miessler
I'm liking your thinking, but does this really simplify things?
m.edmondson
I would say yes. You stated that your main concern was getting rid of the nested case statements which this does...
Abe Miessler
@Abe Miessler - Thats true I did say that, Ill mark your answer up.
m.edmondson
It's somewhat hacky, but the only "simpler" answer that's available. +1 from me
WoLpH
Looks like this is the simplest it can get. Bit of a shame really, I thought there would be a more 'elegant' way.
m.edmondson
+1  A: 

OK, I'm going to play some math games here and take advantage of the fact that y*(x-1)-y = y*(x-2).

EDIT: Realized I had my (SGROUPS-1) vs. (SGROUPS-2) logic backwards and fixed.

update table1.dbo.totals
    set @FEE = @GROUPPRICE * isnull(g.SGROUPS-1,0) - case when isnull(CHARINDEX('JMCG', g.GROUPS),0)>0 then g.SGROUPS else 0 end
from @GROUPMEM as g

if @FEE < 0
begin
    set @GROUPFEE = 0
end
Joe Stefanelli
+1  A: 

For no CASE statements at all, try:

update table1.dbo.totals
set @FEE = @GROUPPRICE * isnull(nullif(sign(g.SGROUPS-1),-1),0)
               * (isnull(g.SGROUPS,0) - 1 - sign(CHARINDEX('JMCG', g.GROUPS))
from @GROUPMEM as g

if @FEE < 0
begin
    set @GROUPFEE = 0
end
Mark Bannister