-1

使用 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;
4

1 回答 1

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  

如果您需要的不止于此,请编辑您的问题,我会尽力为您找到更好的答案。

于 2013-08-17T18:55:32.800 回答