1

我有以下 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)
4

2 回答 2

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 + '%' 
)
于 2013-04-23T14:44:37.237 回答
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 = ''- 我喜欢第一种方法。

于 2013-04-23T14:43:50.517 回答