0

我有一些我试图理解的 SQL 语句(由其他人编写)。在此 SQL 中,它计算“重量”,如下所示。

ISNULL(NULLIF(CASE WHEN ISNULL(m.Override,0) = 1
    THEN m.OverWeight
    ELSE ISNULL(itemWeight.Weight,groupWeight.Weight) END,0),5) AS Weight  

现在我必须在 ASP.net 中使用这个逻辑。因为我是 C#、ASP.net 和 SQL 的新手,所以我在努力。到目前为止,我已经完成了以下操作。

//Calculate weight
    bool override = DataConversion.GetBoolean(row["Override"]);
    decimal overWeight = DataConversion.GetDecimal(row["OverWeight"]);
    decimal itemWeight = DataConversion.GetDecimal(row["ItemWeight"]);
    decimal groupWeight = DataConversion.GetDecimal(row["GroupWeight"]);

    decimal weight= override? DataConversion.GetDecimal(row["OverWeight"]): 5;

    var par = new par(
                Id: DataConversion.GetInt(row["MaterialId"]),
                weight: weight
                );

我面临的问题是:如何ELSE ISNULL(itemWeight.Weight,groupWeight.Weight在条件语句中使用?即decimal weight= override?DataConversion.GetDecimal(row["OverWeight"]): 5;

4

1 回答 1

2

我发现使用更好的格式更容易处理 - 清楚地说明了哪些内容:

ISNULL(
    NULLIF(
        CASE
            WHEN ISNULL(m.Override,0) = 1
                THEN m.OverWeight
            ELSE 
                ISNULL(itemWeight.Weight,groupWeight.Weight)
        END,
        0
    ),
    5
) AS Weight

现在只需使用 ISNULL 和 NULLIF 的定义,我就得到了以下代码:

decimal weight;                        //  AS Weight

if (override != null && override == 1) // WHEN ISNULL(m.Override,0) = 1
{
    weight = overWeight;               // THEN m.OverWeight
}
else
{
    if (itemWeight != null)            // ELSE ISNULL(...)
        weight = itemWeight;           // itemWeight.Weight
    else
        weight = groupWeight;          // groupWeight.Weight
}

if (weight == 0)                       // NULLIF(..., 0)
{
    weight = 5;                        // ISNULL(..., 5)
}

不过,您需要针对实际的 DBNull 进行测试,这取决于您的数据来自哪里。

于 2017-05-11T16:25:41.363 回答