SQL - 带有CASE语句的WHERE

时间:2017-09-25 18:25:58

标签: sql sql-server case where

android:focusable="false"

我想根据 SELECT TOP 1 CostValue FROM [~client_table~].[dbo].[CostRules] AS CostRule WHERE (CASE WHEN DATALENGTH(CostRule.ModelName) = 0 THEN CostRule.Type = 1 AND CostRule.Manufacturer = Printer.ManufacturerId AND CostRule.ColorType = 1 ELSE CostRule.Type = 2 AND CostRule.ModelName = Printer.ModelName AND CostRule.ColorType = 1 END ) ) AS MonoCost 的数据长度定义我的where语句。但是我收到了一个错误:CostRule.ModelName。在Incorrect syntax near '='中我在CostRule.Type = 1语句中出错。

4 个答案:

答案 0 :(得分:4)

必须是这样的:

...
WHERE
  (DATALENGTH(CostRule.ModelName) = 0
    AND CostRule.Type = 1
    AND CostRule.Manufacturer = Printer.ManufacturerId
    AND CostRule.ColorType = 1)
  OR
  (DATALENGTH(CostRule.ModelName) != 0
    AND CostRule.Type = 2
    AND CostRule.ModelName = Printer.ModelName
    AND CostRule.ColorType = 1)

查询中的CASE - 样式无效。

答案 1 :(得分:1)

你可以改变你的陈述:

SELECT TOP 1
    CostValue 
FROM 
    [~client_table~].[dbo].[CostRules] AS CostRule 
WHERE CostRule.ColorType=1
AND CostRule.Type=CASE WHEN  DATALENGTH(CostRule.ModelName) = 0  THEN 1 ELSE 2 END 
AND CostRule.Manufacturer=CASE WHEN  DATALENGTH(CostRule.ModelName) = 0 THEN Printer.ManufacturerId ELSE  Printer.ModelName END 

答案 2 :(得分:0)

您无法使用CASE语句来定义此类条件。使用一些布尔逻辑

会更容易
SELECT *
FROM your_table
WHERE (DATALENGTH(CostRule.ModelName) = 0 
       AND CostRule.Type = 1
       AND CostRule.Manufacturer = Printer.ManufacturerId
       AND CostRule.ColorType = 1)
OR (DATALENGTH(CostRule.ModelName) != 0
       AND CostRule.Type = 2
       AND CostRule.ModelName = Printer.ModelName
       AND CostRule.ColorType = 1)

还有一些其他内容可以删除(例如CostRule.ColorType = 1,因为它在两个分支中都是相同的)但是我已将它们留在这里以说明如何转换CASE语句进入布尔逻辑集。

答案 3 :(得分:0)

看起来您只需要更改WHERE语句:

看起来您只需要更改WHERE语句以使用OR并删除CASE语句。

(SELECT TOP 1
        CostValue 
    FROM 
        [~client_table~].[dbo].[CostRules] AS CostRule 
    WHERE 
                DATALENGTH(CostRule.ModelName) = 0 
                CostRule.Type = 1
                AND CostRule.Manufacturer = Printer.ManufacturerId
                AND CostRule.ColorType = 1
      OR
                DATALENGTH(CostRule.ModelName) <> 0  
                AND CostRule.Type = 2
                AND CostRule.ModelName = Printer.ModelName
                AND CostRule.ColorType = 1

     ) AS MonoCost