简体   繁体   English

简化此代码

[英]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. 我特别想摆脱那个嵌套的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. 你可能会问什么(g.SGROUPS^1)&1做...如果它有一个值,它基本上将g.SGROUPS转换成一个,允许我们在乘法中使用它。

OK, I'm going to play some math games here and take advantage of the fact that y*(x-1)-y = y*(x-2). 好的,我打算在这里玩一些数学游戏,并利用y *(x-1)-y = y *(x-2)的事实。

EDIT : Realized I had my (SGROUPS-1) vs. (SGROUPS-2) logic backwards and fixed. 编辑 :已实现我的(SGROUPS-1)与(SGROUPS-2)逻辑向后和固定。

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: 对于没有CASE语句,请尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM