检查参数然后使用where条件。 (SQL)

时间:2017-01-18 01:58:52

标签: sql sql-server

我想查看参数。

  • 如果参数为null,则查询表的所有数据。
  • 如果参数不为null,那么xxx =参数。

代码:

DECLARE @div as nvarchar(10) = NULL
DECLARE @dept as nvarchar(10) = NULL

;WITH TB1 AS        
(
    SELECT 
        CONVERT(VARCHAR,CHECKTIME,112) CHECKTIME , USERID
    FROM 
        HRM_WORKINGTIME 
    WHERE 
        INOUT IS NULL
    GROUP BY 
        CONVERT(VARCHAR, CHECKTIME, 112), USERID  
)
SELECT  
    EM.EMPID, 
    (EM.FIRSTNAME + ' ' + EM.LASTNAME) AS NAME, 
    PM.POSITIONDESCRIPTION [POSITION],
    DM.DIVDESCRIPTION [DIVISION], 
    EM.DEPTCODE, DE.DEPTDESCRIPTION [DEPTARTMENT],
    WT.CHECKTIME, WT.INOUT, WT.SENSORID, WT.SN, WT.STAT, UI.USERID
FROM    
    HRM_WORKINGTIME WT 
RIGHT JOIN   
    TB1 WT2 ON  CONVERT(VARCHAR, WT.CHECKTIME, 112) = CONVERT(VARCHAR, WT2.CHECKTIME, 112)
            AND WT.USERID = WT2.USERID 
LEFT JOIN 
    USERINFO UI ON WT.USERID = UI.USERID
LEFT JOIN 
    HRM_EMP_MST EM ON EM.EMPID = UI.BADGENUMBER
LEFT JOIN 
    HRM_DIVISION_MST DM ON DM.DIVCODE = EM.DIVCODE
LEFT JOIN 
    HRM_DEPT_MST DE ON DE.DEPTCODE = EM.DEPTCODE
LEFT JOIN 
    HRM_POSITION_MST PM ON PM.POSITIONCODE = EM.POSITIONCODE
WHERE   
    EM.EMPID IS NOT NULL 
    AND CONVERT(VARCHAR, WT2.CHECKTIME, 112) >= '20170101' 
    AND CONVERT(VARCHAR, WT2.CHECKTIME, 112) <= '20170115'
    AND EM.DIVCODE = CASE 
                        WHEN @div IS NULL THEN EM.DIVCODE 
                        ELSE @div 
                     END
    --AND EM.DEPTCODE  = CASE WHEN @dept IS NULL THEN EM.DEPTCODE ELSE @dept END  -- If I use this where dept code is null not show.
ORDER BY 
    EMPID, CHECKTIME ASC

1 个答案:

答案 0 :(得分:1)

IF (parameter IS NULL)
BEGIN
   SELECT
   ...
END
ELSE
BEGIN
   SELECT
   ...
   WHERE (xxx=parameter)
END