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
开发者_Go百科
I'm particularly wanting to get rid of that nested CASE. Any suggestions?
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.
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
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
精彩评论