如何在where部分使用coalesce in

时间:2012-03-08 07:52:02

标签: sql-server sql-server-2008

如何在以下代码中使用Coalesce命令

 PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = @PIECE_ID  AND B.BRAND_ID=COALESCE(B.BRAND_ID,@BRAND_ID)) 

在此代码中

SELECT DISTINCT
            [dbo].[test2](A.PIECE_DETAIL  ) TOTAL_QUANTITY,
            PIECE_LATIN = (SELECT PIECE_LATIN  FROM PIECES WHERE PIECE_ID = 
                     (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
            BRAND_LATIN = (SELECT BRAND_LATIN FROM BRANDS WHERE BRAND_ID = 
                     (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
            BRAND_ID = (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
            PIECE_ID = (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),          
            MODEL_NAME = (SELECT MODEL_NAME  FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
            PIECE_DETAIL MODEL_ID,
            A.PIECE_STATUS ,
            PIECE_STATUS_Name  = (SELECT STATUS_Name  FROM PIECE_STATUS WHERE STATUS_ID = A.PIECE_STATUS) ,
            A.PIECE_DETAIL
        FROM DOCUMENT_ITEMS A
        WHERE 
        PIECE_STATUS = 1 and
        DOC_SEQ IN (SELECT DOC_SEQ FROM DOCUMENT_HEADER WHERE DOC_TYPE IN (1,3)) 
        AND PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = @PIECE_ID  AND B.BRAND_ID=COALESCE(B.BRAND_ID,@BRAND_ID)) 
        AND [DBO].[GET_WAREHOUSE_QUANTITIES_SPECIAL_ID_EXIST](A.PIECE_DETAIL ,A.SPECIAL_ID )> 0
        GROUP BY PIECE_DETAIL ,SPECIAL_ID ,PIECE_STATUS

感谢所有

1 个答案:

答案 0 :(得分:1)

那样的话:

WHERE PIECE_DETAIL IN
    (
        SELECT 
            coalesce(PIECE_DETAIL,B.MODEL_ID) 
        FROM 
            PIECES_DETAILS B 
        WHERE 
            PIECE_ID = @PIECE_ID  
            AND B.BRAND_ID=COALESCE(B.BRAND_ID,@BRAND_ID)
    )

修改

也许是这样的:

WHERE
    (
        (
            FROM_DATE IS NULL AND TO_DATE IS NULL
        )
        OR 
        (
            BUY_DOC_DATE BETWEEN FROM_DATE AND TO_DATE
        )
    )