2010-11-11 94 views
0

SQL2008。我有一个表中需要重写的值,并且遵循一系列规则。规则在另一个表中。SQL。分层次应用业务规则

但是规则是分层的,即 - 我需要在主表中的每一行应用最严格的所有适用规则。

下面是示例...规则表(B和C可以是NULLS)

A B C Value 
1 2 3 100 
1 2 NULL 80 
1 NULL NULL 60 

Main Table 
A  B  C  Value OverridenValue 
1  2  3  1  100 
1  2  2  2  80 
1  3  1  3  60 
3  1  3  4  4 <- no override as no rule found 
NULL NULL NULL 5  5 <- no override as no rule found 

我需要一个标量函数即fnGetOverridenValue(@A INT,@B INT,@ C INT)退货浮动

回答

0
Select m.A, m.B, m.C, m.[Value], 
    Case 
    When Not IsNull(r1.Value) Then r1.Value 
    When Not IsNull(r2.Value) Then r2.Value 
    When Not IsNull(r3.Value) Then r3.Value 
    Else m.[Value] 
    End as Overriddenvalue 
From 
    MainTable m 
    Left Join RulesTable r1 on m.A=r1.A and m.B=r1.B and m.C=r1.C 
    Left Join RulesTable r2 on m.A=r2.A and m.B=r2.B and r2.C is NULL 
    Left Join RulesTable r3 on m.A=r3.A and r3.B is NULL and r3.C is NULL