简体   繁体   中英

How Can I Set Value To output parameter in sql stored procedure within select statement?

I have Stored Procedure in sql server 2008 used to paginating data returned from product table in database. what i want is return total pages count in the same select statement

ALTER PROCEDURE [dbo].[SP_GetProducts]
    @PageSize int = 10, 
    @PageNumber int = 1,
    @ProductCode nvarchar(50) = null,
    @ProductName nvarchar(100) = null,
    @TotalPages int = null output 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


    SELECT TOP (@PageSize) *, @TotalPages = COUNT(*)  FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY ProductId ASC) offset, * FROM (
         SELECT *, count(*) over() AS TotalRows
         FROM Products
        ) myquery
        ) paginator
        WHERE offset >= (((@PageSize * @PageNumber) - @PageSize)) +1 and offset <= (@PageSize * @PageNumber)

you cannot retrieve values from a Select statement and assign value to a variable at the same time. In your particular case since you are only assigning the number or rows returned from your select statement you can use a slightly different approach to get what you want.

ALTER PROCEDURE [dbo].[SP_GetProducts]
    @PageSize int = 10, 
    @PageNumber int = 1,
    @ProductCode nvarchar(50) = null,
    @ProductName nvarchar(100) = null,
    @TotalPages int = null output 
AS
BEGIN
    SET NOCOUNT ON;

    SELECT TOP (@PageSize) * 
     FROM (
           SELECT ROW_NUMBER() OVER (ORDER BY ProductId ASC) offset, * 
              FROM (
                    SELECT *, count(*) over() AS TotalRows
                    FROM Products
           ) myquery
        ) paginator
        WHERE offset >= (((@PageSize * @PageNumber) - @PageSize)) +1 
         AND offset <= (@PageSize * @PageNumber)

    -- here assign value to your output parameter using the following

     SELECT @TotalPages = @@ROWCOUNT;
END

Note

Avoid using SELECT * instead use Column names, only the columns you actually want to retrieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM