I created a stored procedure but the search is not working. I tried passing different values, but it is always returning the same values.
Here is my stored procedure:
CREATE OR ALTER PROCEDURE [dbo].[users]
@SEARCH VARCHAR(100)='', -- Gloabl filter
@PageNumber INT,
@PageSize INT,
@SortOrder VARCHAR(10),
@SortColumn INT
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
DECLARE @RecordFrom INT;
SET @RecordFrom = (@PageNumber-1) * @PageSize;
;WITH CTE_Result (id, name, email, department) AS
(
SELECT *
FROM dbo.users
WHERE 1=1
AND (@SEARCH = '' OR (@SEARCH != '' AND (
name LIKE '%' + @SEARCH + '%'
OR email LIKE '%' + @search + '%'
)))
),
CTE_Count AS
(
SELECT COUNT(id) AS TotalRecords
FROM CTE_Result
)
SELECT *
FROM CTE_Result, CTE_Count
ORDER BY
CASE WHEN @SortColumn = 1 AND @SortOrder = 'asc' THEN id
END ASC,
CASE WHEN @SortColumn = 1 AND @SortOrder = 'desc' THEN id END DESC,
OFFSET @RecordFrom ROWS
FETCH NEXT @PageSize ROWS ONLY
END TRY
BEGIN CATCH
THROW;
END CATCH
SET NOCOUNT OFF
END
What is wrong here? I can't seem to figure it out, the code looks correct to me.
2条答案
按热度按时间muk1a3rh1#
Try "With Recompile". I've only used it when the stored procedure is overly optimising and resulting in some queries being slow, but it could be your issue:
0lvr5msh2#
After fixing "Cannot perform alter on 'dbo.users' because it is an incompatible object type." (
users
is already an existing object?),and "Incorrect syntax near '@RecordFrom'." (removing the
,
afterDESC
)and, of course, the old-style JOIN is also fixed...
I created some sample data:
I do have the following code which seems to work:
output (2 of the 3 record in my test data):
when querying:
EXEC [usersXYZ] 'a',1,10,"1",5
see: DBFIDDLE