【问题标题】:case statement returns multiple rowscase 语句返回多行
【发布时间】:2011-12-29 07:46:15
【问题描述】:

我想在 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 个值。当子查询跟随 =、!=、、>= 或使用子查询时,这是不允许的 作为表达式。

【问题讨论】:

    标签: sql-server subquery case-statement


    【解决方案1】:

    SQL Server 中的 CASE 不是流控制语句(它与 C# 中的 switch 语句不同) - 它只是用于返回几个可能值之一。

    需要在T-SQL中使用IF语句

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

    或类似的东西。

    【讨论】:

    • 其实我不想写多个查询。我想将上述查询的结果集用于另一个子查询。
    • @Abhi:您不能以这种方式使用CASE - 它只能返回单个值。如果您有可能返回多个值的子查询 - 您不能使用 CASE 来处理此问题
    【解决方案2】:

    你没有正确使用case语句,请看documentation。

    你能用这样的查询来管理吗:

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

    【讨论】:

    • 当子查询仅返回 1 行时,我的查询工作正常。但是当子查询返回多行时它会失败。你能告诉我写查询的确切方法吗?
    【解决方案3】:

    我得到了解决方案。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2012-07-07
      相关资源
      最近更新 更多