2011-12-29 170 views
1

我想在case語句中返回多行。可能嗎?或者有沒有其他方法可以做到這一點?case語句返回多行

select 
    case 
     when 3 = 1 
      then (select orderid from order_master where noOfInstallment = installmentPaid) 
     else 
      (select orderid from order_master where noOfInstallment <> installmentPaid) 
    END 

這兩個子查詢都返回多行。現在上面的查詢顯示以下錯誤。

子查詢返回的值超過1。當子查詢遵循=,!=,<,< =,>,> =或子查詢被用作表達式時,這是不允許的。

回答

0

我得到了解決。

SELECT o.* FROM Order_Master as o Where 
    (
     ((@paymentStatus = 0) AND (o.noOfInstallment <> o.installmentPaid)) 
     OR 
     ((@paymentStatus=1) AND (o.noOfInstallment = o.installmentPaid)) 
    ) 
2

情況下,SQL Server是流量控制語句(這比在C#中switch說法不同) - 它只是用來返回幾個可能的值之一。

您需要使用IF語句在T-SQL

IF 3 = 1 
    select orderid from order_master where noOfInstallment = installmentPaid 
ELSE 
    select orderid from order_master where noOfInstallment <> installmentPaid 

或類似這樣的東西。

+0

其實我不想寫多個查詢。我想使用上面查詢的resultset到另一個子查詢。 – Abhi 2011-12-29 08:03:15

+0

@Abhi:你不能以這種方式使用CASE,它只能返回**一個值**。如果你有可能返回多個值的子查詢 - 你不能使用'CASE'來處理這個 – 2011-12-29 08:27:08

0

您沒有正確使用該案例陳述,請在documentation上採訪。

你可以管理與這樣的查詢:

select orderid, 
    case 
     when (noOfInstallment = installmentPaid) then 
     'equal' 
     else 
     'not equal' 
    END 
from order_master 
+0

當子查詢只返回1行時,我的查詢工作正常。但當子查詢返回多行時失敗。你能給我準確的方式來寫查詢嗎? – Abhi 2011-12-29 08:09:19