如何在使用ROW_NUMBER()&时设置out参数计数(*)

时间:2013-08-17 17:59:40

标签: sql sql-server tsql stored-procedures

当使用ROW_NUMBER()OVER和COUNT(*)时,如何设置此tsql proc的out @Total参数?

    ALTER proc [Generic].[proc_GetPartsForUser_BySupplier_ByCategory]
@UserID      UNIQUEIDENTIFIER,
@SupplierID  INT,
@CategoryID  INT,
@StartIndex  INT, 
@PageSize    INT, 
@Total       INT out
AS
SET NOCOUNT ON;

SET @StartIndex = @StartIndex + 1
BEGIN
            SELECT *
            FROM (
             SELECT *, ROW_NUMBER() OVER (ORDER BY ID ASC) AS RowNum, COUNT(*) OVER() AS Total
             FROM (
                            SELECT p.*,
                                   s.Name'SupplierName',s.Email'SupplierEmail',s.Phone'SupplierPhone'

                              FROM [Generic].[Part] p  WITH(NOLOCK)                         JOIN
                                   Generic.Supplier s  WITH(NOLOCK) ON p.SupplierID = s.ID

                              WHERE p.ID  IN(SELECT up.PartID FROM Generic.GenericCatalog gc with(nolock) JOIN
                                                Generic.UserPart up WITH(NOLOCK) ON up.GenericCatID = gc.ID
                                                WHERE gc.UserID = @UserID)
                              AND
                              CategoryID = @CategoryID
                              AND
                              s.ID = @SupplierID
            ) AS firstt
            ) AS final
         WHERE RowNum BETWEEN @StartIndex AND (@StartIndex + @pageSize) - 1

            ORDER BY final.[Name] ASC;

END;
SET NOCOUNT OFF;

1 个答案:

答案 0 :(得分:3)

简单的答案是你不能! OVER()子句创建一个窗口函数,这意味着它将返回每一行的值!该参数只能存储一个值!

问题仍然存在,你为什么要这样做? 如果整个查询的要点是返回COUNT(*)的值,那么只需使用它而没有OVER子句,如下所示:

SELECT @Total = COUNT(*) 
FROM   (SELECT p.*, 
               s.NAME 'SupplierName', 
               s.EMAIL'SupplierEmail', 
               s.PHONE'SupplierPhone' 
        FROM   [Generic].[PART] p WITH(NOLOCK) 
               JOIN GENERIC.SUPPLIER s WITH(NOLOCK) 
                 ON p.SUPPLIERID = s.ID 
        WHERE  p.ID IN(SELECT up.PARTID 
                       FROM   GENERIC.GENERICCATALOG gc WITH(NOLOCK) 
                              JOIN GENERIC.USERPART up WITH(NOLOCK) 
                                ON up.GENERICCATID = gc.ID 
                       WHERE  gc.USERID = @UserID) 
               AND CATEGORYID = @CategoryID 
               AND s.ID = @SupplierID) AS firstt  

如果您需要的不仅仅是这个,请编辑您的问题,我会尽力为您找到更好的答案。