子查询返回的值超过1。如果陈述

时间:2016-12-27 21:49:25

标签: sql sql-server

如果条件等于真,那么我想乘法 (od.price * od.kilo),然后带上其他字段 其他

我想乘法(od.quant * od.price)然后带其他字段

创建PROC GET_ORDER_ACCOUNT_DETAILS     @ORDERID INT

AS 
 BEGIN
        IF((SELECT calcType FROM orderDetailsTBL od WHERE od.orderID = @ORDERID) = 'K') 
            BEGIN
            SELECT
            (SELECT od.price * od.kilo FROM orderDetailsTBL od) as "AMOUNT",

            od.quant as "QUANTITY" , 
            od.kilo as "KILO" ,
            od.price as "PRICE" ,
            od.calcType as "UNIT" ,
            p.prodName as "NAME" ,
            od.recivedID as "RECIVED"
FROM orderAccTBL oa
JOIN orderDetailsTBL od ON od.orderID = oa.orderID
JOIN productTBL p ON p.prodID = od.productID
WHERE
        oa.orderID = @ORDERID
                    END
            ELSE

            BEGIN
            SELECT
            (SELECT od.quant * od.price FROM orderDetailsTBL od) as "AMOUNT",
            od.quant as "QUANTITY" , 
            od.kilo as "KILO" ,
            od.price as "PRICE" ,
            od.calcType as "UNIT" ,
            p.prodName as "NAME" ,
            od.recivedID as "RECIVED"
FROM orderAccTBL oa
JOIN orderDetailsTBL od ON od.orderID = oa.orderID
JOIN productTBL p ON p.prodID = od.productID
WHERE
        oa.orderID = @ORDERID
            END

    END     

1 个答案:

答案 0 :(得分:1)

您不需要任何这些IF..ELSE语句,甚至您的选择中的子查询,您可以通过以下简单的选择查询来实现:

CREATE PROC GET_ORDER_ACCOUNT_DETAILS
 @ORDERID INT
AS 
BEGIN
 SET NOCOUNT ON;

    SELECT
          CASE 
               WHEN od.calcType = 'K'  
               THEN od.price * od.kilo 
               ELSE od.quant * od.price 
           END          as [AMOUNT]
         ,od.quant      as [QUANTITY] 
         ,od.kilo       as [KILO] 
         ,od.price      as [PRICE] 
         ,od.calcType   as [UNIT] 
         ,p.prodName    as [NAME] 
         ,od.recivedID  as [RECIVED]
    FROM       orderAccTBL     oa
    INNER JOIN orderDetailsTBL od ON od.orderID = oa.orderID
    INNER JOIN productTBL      p  ON p.prodID = od.productID
    WHERE oa.orderID = @ORDERID

END