如果填充参数,则使用过滤器选择ROW_NUMBER()?

时间:2013-04-23 14:36:33

标签: sql-server sql-server-2008

我有以下SQL Server 2008查询。我想对其进行扩充,以便在填充@Filter参数时将该值传递给每个字段(跨列)。如果没有过滤器,查询将完美运行。我不确定过滤器是否应该放在我拥有的地方。任何帮助将不胜感激:

ALTER PROCEDURE [dbo].[pd_Get_Team2]
@OutTotalRecCount INT OUTPUT, 
@CurrentPage INT, 
@PageSize INT, 
@Token as nvarchar(50),
@UserID as nvarchar(50),
@SortDirection INT,
@SortField nvarchar(50),
@Filter nvarchar(50)

AS     
SELECT * FROM          
(SELECT ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @SortDirection = 1 AND @SortField = 1 THEN pd_Role.UserID END ASC, 
CASE WHEN @SortDirection = 2 AND @SortField = 1 THEN pd_Role.UserID END DESC
) AS Row, 
pd_Role.id,      
pd_Role.Edit_Rights, 
pd_Role.UserID, 
pd_Role.Is_Approved, 
pd_Role.Login_Date, 
pd_Role.Team  

FROM pd_Role INNER JOIN  
pd_Token ON pd_Role.Token = pd_Token.Token 
WHERE 
(pd_Token.Token = @Token) AND (pd_Token.UserID = @UserID) 

 --how do I structure a filter on these fields if the filter is populated?
 --CASE WHEN LEN(@Filter)> 1  
 --AND pd_Role.Edit_Rights LIKE '%' + @Filter + '%' OR 
 --AND pd_Role.UserID LIKE '%' + @Filter + '%' OR 
 --AND pd_Role.Team LIKE '%' + @Filter + '%' 
 --
  ) 
  AS TeamWithRowNumbers 
  WHERE  Row >= (@CurrentPage - 1) * @PageSize + 1 AND Row <= @CurrentPage*@PageSize     

  SELECT @OutTotalRecCount = COUNT(*) FROM pd_Role 
  WHERE (pd_Role.Token = @Token)

2 个答案:

答案 0 :(得分:2)

如果@Filter永远不为NULL(但可能为空):

WHERE 
(pd_Token.Token = @Token) AND (pd_Token.UserID = @UserID) 

AND (
    pd_Role.Edit_Rights LIKE '%' + @Filter + '%' -- '%' + '' + '%' = Matches all
    OR pd_Role.UserID LIKE '%' + @Filter + '%'
    OR pd_Role.Team LIKE '%' + @Filter + '%' 
)

答案 1 :(得分:1)

试试这个:

AND ((@Filter IS NULL) OR
  (pd_Role.Edit_Rights LIKE '%' + @Filter + '%' OR 
   AND pd_Role.UserID LIKE '%' + @Filter + '%' OR 
   AND pd_Role.Team LIKE '%' + @Filter + '%')
)

确保@Filter在未提供时为空,或使用@Filter = '' - 我喜欢第一种方法。