如何以正确的语法或正确的方式进行此查询?

时间:2010-05-16 18:22:31

标签: sql sql-server tsql

我使用t-sql编写此查询并给我一个错误(关键字'OR'附近的语法不正确) 如何以正确的方式写出来?

SELECT SUM(Quantity) 
  FROM   Invoices
 WHERE  Invoices.InvoiceDocStatusID = 
        CASE @InventoryType
                      WHEN 1 
                      THEN ((2)OR(1))
                      ELSE 2
                    END

2 个答案:

答案 0 :(得分:2)

不是那种确定的语义。您是否总是希望与InvoiceDocStatusID=2匹配@InventoryType的行,而不管InvoiceDocStatusID=1的价值是什么?另外还要@InventoryType = 1哪里有SELECT SUM(Quantity) FROM Invoices WHERE (Invoices.InvoiceDocStatusID = 1 AND @InventoryType = 1) OR Invoices.InvoiceDocStatusID = 2

{{1}}

答案 1 :(得分:1)

  • 您一直在检查Invoices.InvoiceDocStatusID = 2
  • 唯一的开关是@InventoryType
  • 不需要ELSE子句:它变为NULL

因此...

SELECT SUM(Quantity) 
FROM Invoices
WHERE Invoices.InvoiceDocStatusID IN (2, CASE @InventoryType WHEN 1 THEN 1 END)