存储过程中的高级折扣系统

时间:2014-06-25 11:53:36

标签: sql-server-2008 stored-procedures calculated-columns discount

我正在制作月度销售的存储过程。在存储过程中,我们有折扣。此折扣可以从三个不同的表中获取。如果折扣不在id.rabatt中,它应该从dp.rabatt获取,如果它不在那里,它应该从ds.rabatt获取。所以前两个可以是空的,而最后一个总是有折扣..

我在设计WHEN部分程序时遇到大麻烦。如果你有时间,请看看并帮我上路:

                     CASE (
                 when 
                Isnull(id.rabatt, Isnull(u.rabatt, id.rabatt)) then.. 
                when 
                 Isnull(dp.rabatt, Isnull(x.rabatt, dp.rabatt)) then..
                 when 
                 Isnull(ds.rabatt, Isnull(y.rabatt, ds.rabatt)) then..
                 end)
                 AS 'Discount', 

我必须使用Isnull的原因是在每个Discount表中,我还有两个不同的折扣,一个永远持续(2999)和一个选定的期间。就像我在这里展示的那样:

           LEFT OUTER JOIN discount AS id 
                    ON id.identifiers = isa.identifiers 
                       AND id.store = BV.name 
                       AND id.from_date <= isa.sales_date 
                       AND id.to_date >= isa.sales_date 
                       AND id.to_date < '2999-01-01' 
       LEFT OUTER JOIN discount AS u 
                    ON u.identifiers = isa.identifiers 
                       AND u.to_date = '2999-01-01' 

另外两张表的设计方式类似。

1 个答案:

答案 0 :(得分:1)

您可以使用与使用IsNull函数类似的方式使用coalesce函数。 IsNull和Coalesce之间存在一些细微的差别,但是对您的代码有益的显着差异是您可以拥有多个参数而无需嵌套它。

您的代码: Isnull(id.rabatt,Isnull(u.rabatt,id.rabatt))

与以下相同: Coalesce(id.rabatt,u.rabatt,id.rabatt)

下一步...案例/何时有2种一般形式。

Case (Some Condition)
     When (Value 1) Then ...
     When (Value 2) Then ...
     Else (Default Value)
     End

或者

Case When (SomeCondition = Value1) Then ...
     When (SomeCondition = Value2) Then ...
     Else DefaultValue
     End

查看您的代码段,看起来好像您使用的是第二种形式,但您在when部分中没有比较运算符。我想你想要这样的......

CASE When Coalesce(id.rabatt, u.rabatt, id.rabatt) Is Not NULL then.. 
     When Coalesce(dp.rabatt, x.rabatt, id.rabatt) Is Not NULL then..
     When Coalesce(ds.rabatt, y.rabatt, id.rabatt) Is Not NULL then..
     Else (Put a default value here)
     end AS [Discount]
相关问题