如何在存储过程中的查询中设置输出参数值

时间:2018-07-18 06:58:45

标签: sql sql-server

我有存储过程,并且我想要参数@OUT_TOTALROWS

ALTER PROCEDURE [dbo].[P_SOMEPROC](@IN_USERID INT,  
                                        @IN_SEARCHFILTER VARCHAR(50),
                                        @IN_DELIVERYSTATUS TINYINT,
                                        @IN_PAGESKIP INT = NULL,
                                        @IN_PAGENEXT INT = NULL)
                                        @OUT_TOTALROWS INT OUTPUT) --TOTAL ROWS OUT HERE

-- ******** HOW TO SET @OUT_TOTALROWS FROM HERE?
SELECT COUNT(*) OVER() AS TotalRows, --IS THERE A BEGIN WAY? DONT WANT THIS
       P.NAME
    FROM SOMETABLE PM
    join SOMETABLE_2 P ON P.ID = PM.ID
    WHERE PM.UserID = @IN_USERID AND 
    PM.DeliveryStatus = @IN_DELIVERYSTATUS AND
    (CONCAT(P.FirstName, ' ', P.LastName) LIKE '%' + @IN_SEARCHFILTER + '%' OR
    PM.Message LIKE '%' + @IN_SEARCHFILTER + '%')
    ORDER BY PM.ScheduledDate DESC OFFSET @IN_PAGESKIP ROWS FETCH NEXT @IN_PAGENEXT ROWS ONLY;

因此,我想知道在应用偏移量之前的总行数,并希望将其作为输出参数以及检索到的数据返回。

是否有更好的方法来获得@OUT_TOTALROWS的设置?

1 个答案:

答案 0 :(得分:0)

select列将所需的全部内容包含到temp表中,然后可以在一个@OUT_TOTALROWS中设置select变量,其他查询将成为您的结果集。

SELECT PM.ScheduledDate,P.NAME 
INTO #TEMP
FROM SOMETABLE PM
join SOMETABLE_2 P ON P.ID = PM.ID
WHERE PM.UserID = @IN_USERID AND 
PM.DeliveryStatus = @IN_DELIVERYSTATUS AND
(CONCAT(P.FirstName, ' ', P.LastName) LIKE '%' + @IN_SEARCHFILTER + '%' OR
PM.Message LIKE '%' + @IN_SEARCHFILTER + '%')


SELECT @OUT_TOTALROWS = COUNT(*) 
FROM #TEMP

SELECT 
   COUNT(*) OVER() AS TotalRows, --IS THERE A BEGIN WAY? DONT WANT THIS
   t.NAME
FROM #TEMP t
ORDER BY t.ScheduledDate DESC 
OFFSET @IN_PAGESKIP ROWS FETCH NEXT @IN_PAGENEXT ROWS ONLY;

IF OBJECT_ID('tempdb.dbo.#TEMP', 'U') IS NOT NULL
  DROP TABLE #TEMP;