1
CREATE PROCEDURE [dbo].[rpt_Report]
   @Product varchar(20) = NULL,
   @From DateTime = null,
   @To DateTime = null
AS
BEGIN
    SELECT 
       CO.PO, CO.DLVRY,   
       CASE
          WHEN co.CUST_ID = '120' THEN '120' 
          WHEN HDR.PO_NO LIKE 'CL%' THEN 'CL'
          WHEN RED.REU = 'SK' THEN 'STOCK' 
          WHEN RED.REU = 'SM' THEN 'ORTS' 
          WHEN co.ITEM = 'PW%' THEN 'CHAIN' 
          WHEN co.ITEM LIKE 'D%' THEN 'VAN' ELSE 'MISC' 
       END AS PRODUCT 
     FROM   
        co AS co    
     INNER JOIN 
        HDR AS HDR ON co.NUMBER = HDR.NUMBER 
     INNER JOIN 
        RED AS RED ON co.ITEM = RED.ITEM 
     WHERE   
        (co.DLVRY BETWEEN @From AND @To) AND (@Product = PRODUCT)
     ORDER BY
        co.DLVRY DESC
END

当我执行它时,我收到一条错误消息

消息 207,级别 16,状态 1,过程 rpt_Report,第 34 行
无效的列名称“产品”。

我应该使用 case 字段值作为 where CLAUSE 中的参数。

4

2 回答 2

1

您似乎正在尝试PRODUCT在子句中使用别名WHERE,但您不能这样做。因此,您可以将查询包装在子查询中以使用别名:

CREATE PROCEDURE [dbo].[rpt_Report]
   @Product varchar(20) = NULL,
   @From DateTime = null,
   @To DateTime = null
AS
BEGIN
    SELECT x.PO, x.DLVRY, x.PRODUCT
    FROM
    (
        SELECT CO.PO, CO.DLVRY,   
           CASE
              WHEN co.CUST_ID = '120' THEN '120' 
              WHEN HDR.PO_NO LIKE 'CL%' THEN 'CL'
              WHEN RED.REU = 'SK' THEN 'STOCK' 
              WHEN RED.REU = 'SM' THEN 'ORTS' 
              WHEN co.ITEM = 'PW%' THEN 'CHAIN' 
              WHEN co.ITEM LIKE 'D%' THEN 'VAN' ELSE 'MISC' 
           END AS PRODUCT 
         FROM  co AS co    
         INNER JOIN HDR AS HDR 
            ON co.NUMBER = HDR.NUMBER 
         INNER JOIN RED AS RED 
            ON co.ITEM = RED.ITEM 
    ) x        
    WHERE (x.DLVRY BETWEEN @From AND @To) 
        AND (@Product = PRODUCT)
    ORDER BY x.DLVRY DESC
END
于 2012-09-27T18:41:06.023 回答
0

试试这个:

SELECT 
   CO.PO, CO.DLVRY,   
   PRODUCT = CASE
                WHEN co.CUST_ID = '120' THEN '120' 
                WHEN HDR.PO_NO LIKE 'CL%' THEN 'CL'
                WHEN RED.REU = 'SK' THEN 'STOCK' 
                WHEN RED.REU = 'SM' THEN 'ORTS' 
                WHEN co.ITEM = 'PW%' THEN 'CHAIN' 
                WHEN co.ITEM LIKE 'D%' THEN 'VAN' ELSE 'MISC' 
             END 
 FROM   
    co AS co    
 INNER JOIN 
    HDR AS HDR ON co.NUMBER = HDR.NUMBER 
 INNER JOIN 
    RED AS RED ON co.ITEM = RED.ITEM 
 WHERE   
    (co.DLVRY BETWEEN @From AND @To) AND (@Product = PRODUCT)
 ORDER BY
    co.DLVRY DESC

希望这会有所帮助!

于 2012-09-27T18:20:11.073 回答