如果变量不为空,则使用where子句查询

时间:2018-09-05 14:33:02

标签: sql sql-server tsql stored-procedures

我试图查询没有成功,我想做的是这样:

ALTER PROCEDURE [dbo].[spPagination] -- ORDER BY id
    @filterCol NVARCHAR(20) = NULL, --<<<<
    @filterValue NVARCHAR(40) = NULL, --<<<<
    @PageNumber INT,
    @PageSize INT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT      
        Emp.id , Emp.email, Emp.[firstName], Emp.[lastName], Emp.[salary], 
        Emp.[startDateWork], Emp.age, Rol.[name] AS Role
    FROM        
        [dbo].tblEmployees5m Emp
    INNER JOIN
        [dbo].[tblRoles] Rol ON Emp.roleId = Rol.id
    WHERE       
        @filterCol LIKE '%' + @filterValue + '%' --<<<< 
    ORDER BY    
        id
        OFFSET @PageSize * (@PageNumber - 1) ROWS
        FETCH NEXT  @PageSize ROWS ONLY OPTION (RECOMPILE);

    SELECT COUNT(1) AS totalCount 
    FROM [dbo].tblEmployees5m
END

我正在根据@filterCol@filterValue尝试对结果应用过滤器-如果它们不为NULL,那么我想使用where子句返回结果(现在不起作用) )。

ELSE,如果NULL有2个值,则不要应用where子句。 @filterCol将保留列名。 @filterValue将保留列值。

我该如何实现?有更好的方法吗?

我建议使用动态SQL,但我已经读过它,但是我不明白使用它会带来什么好处。这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

Read

ALTER PROCEDURE [dbo].[spPagination] -- ORDER BY id
  @filterCol NVARCHAR(20) = NULL, --<<<<
  @filterValue NVARCHAR(40) = NULL, --<<<<
  @PageNumber INT,
  @PageSize   INT
AS
BEGIN
  SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(max)
    SET @SQL='SELECT      Emp.id , Emp.email, Emp.[firstName], Emp.[lastName], Emp.[salary], Emp.[startDateWork], Emp.age  , Rol.[name] as Role
    FROM        [dbo].tblEmployees5m    Emp
    inner join  [dbo].[tblRoles]        Rol
    ON          Emp.roleId = Rol.id
    WHERE 1=1'

    IF ISNULL(@filterCol,'')!='' AND ISNULL(@filterCol,'')!=''
        SET @SQL= @SQL+' AND @fc LIKE ''%@fv%'''

    SET @SQL = @SQL+' ORDER BY    id'

    IF ISNULL(@PageNumber,'')!='' AND ISNULL(@PageSize,'')!=''
        SET @SQL= @SQL+'
        OFFSET  @PS * (@PN - 1)  ROWS
        FETCH NEXT  @PN ROWS ONLY OPTION (RECOMPILE);'




    EXEC SP_EXECUTESQL @SQL, N'@fc NVARCHAR(20) ,@fv NVARCHAR(40) ,@PN INT,@PS INT',@fc=@filterCol,@fv=@filterValue,@PG=@PageNumber,@PS=@PageSize

    select count(1) as totalCount from [dbo].tblEmployees5m
END