2011-12-29 164 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