2017-09-25 3 views
0
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 

Ich möchte meine WHERE-Anweisung in Abhängigkeit von der Datenlänge von CostRule.ModelName definieren. Aber ich habe einen Fehler: Incorrect syntax near '='. in CostRule.Type = 1 und ich habe einen Fehler in der ELSE Aussage.SQL - WHERE mit CASE-Anweisung

Antwort

4

muss so aussehen:

... 
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) 

Die CASE -Stil aus der Abfrage nicht funktionieren kann.

+0

Das ist was ich will! Vielen Dank. –

0

Sie können keine CASE-Anweisung verwenden, um solche Bedingungen zu definieren. Es wird leichter sein, nur einige der Booleschen Logik

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) 

Es gibt einige andere Dinge, die (wie CostRule.ColorType = 1 da sie die gleiche in beiden Zweigen ist) entfernt werden konnte, aber ich habe sie verlassen, um hier zu veranschaulichen, wie man wandeln Sie Ihre CASE-Anweisung in eine logische Logik um.

1

Sie können Ihre Anweisung wie folgt ändern:

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 
0

Es sieht aus wie Sie gerade die WHERE-Anweisung zu ändern brauchen würde:

Es sieht aus wie Sie gerade Ihre WHERE-Anweisung zu ändern brauchen, um zu verwenden, ODER und entfernen Sie die CASE-Anweisung.

(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