在where子句之前是否可以做

时间:2019-06-28 02:40:49

标签: sql sql-server

我有变量,我只想检查变量是否不是null或空,然后才想启动或包含where子句。这个想法如下。我检查了一下,但是显示语法错误。

    SELECT
        ID,
        BRANCHCODE,
        BRANCHNAME,
        DEPARTMENTCODE,
        DEPARTMENTNAME,
    FROM 
        dbo.RATINGLOGS

    IF (NULLIF(@BRANCHCODE, '') IS NOT NULL)
    BEGIN
        WHERE BRANCHCODE LIKE '%'@BRANCHCODE'%'
    END

    ORDER BY 
    RATINGTIMESTAMP OFFSET @PageSize * (@PageNumber - 1) ROWS 
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE)

2 个答案:

答案 0 :(得分:3)

您只需像这样使用WHERE子句:

WHERE BRANCHCODE LIKE '%' + @BRANCHCODE + '%' OR
      NULLIF(@BRANCHCODE, '') IS NOT NULL

答案 1 :(得分:2)

SELECT
        ID,
        BRANCHCODE,
        BRANCHNAME,
        DEPARTMENTCODE,
        DEPARTMENTNAME,
    FROM 
        dbo.RATINGLOGS   

        WHERE (ISNULL(@BRANCHCODE,'')='' OR  BRANCHCODE LIKE '%'@BRANCHCODE'%')


    ORDER BY 
    RATINGTIMESTAMP OFFSET @PageSize * (@PageNumber - 1) ROWS 
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE)