2013-04-24 64 views
2

我的表格包含約5000行。我想知道表格中的特定行位置。 我的存儲過程是:行號提取

CREATE PROC Sp_getrownumber(@MemberID INT) 
AS 
    SELECT Row_number() 
      OVER ( ORDER BY joiningdate ASC) AS Rownumber, 
      M.memberid, 
      P.name, 
      M.joiningdate 
    FROM tblmemberdata M 
      JOIN tblpersonaldetails P 
      ON M.memberid = P.memberid 

但是,當我米試圖取2特定行,該行沒有被顯示1 的代碼是:

CREATE PROC Sp_getrownumber(@MemberID INT) 
AS 
    SELECT Row_number() 
      OVER ( ORDER BY joiningdate ASC) AS Rownumber, 
      M.memberid, 
      P.name, 
      M.joiningdate 
    FROM tblmemberdata M 
      JOIN tblpersonaldetails P 
      ON M.memberid = P.memberid 
    WHERE M.memberid = @MemberID 

如何獲取確切的行號?

回答

2

其修改爲:

alter proc SP_GetRowNumber 
(@MemberID int) 
as 
SELECT * FROM (
    SELECT 
ROW_NUMBER() OVER (ORDER BY JoiningDate ASC) AS Rownumber, 
M.MemberID,P.Name,M.JoiningDate 
FROM tblMemberData M join tblPersonalDetails P on M.MemberID=P.MemberID 
) AS Counts 
WHERE MemberID = @MemberID 
2

你看到的是因爲ROW_NUMBER()作品在當地SELECT,而不是整個表!

嘗試這一個:

CREATE PROC Sp_getrownumber(@MemberID INT) 
AS 
    SELECT * 
    FROM (
     SELECT Row_number() 
       OVER (ORDER BY joiningdate ASC) AS Rownumber, 
       M.memberid, 
       P.name, 
       M.joiningdate 
     FROM tblmemberdata M 
     JOIN tblpersonaldetails P 
       ON M.memberid = P.memberid 
    ) tblRowCounter 
    WHERE M.memberid = @MemberID; 

什麼此代碼完成是在內存中的表,該表保留原始行號進行濾波。

但是!請注意,在SQL中不是行編號。 SQL只是知道有一大堆屬於表的數據。 OVER條款中的ORDER BY joiningdate ASC聲明是極其重要的!更改該列或添加更多列可能會更改行號。

1
CREATE PROC Sp_getrownumber(@MemberID INT) 
AS 
    ;WITH Numbered AS (
     SELECT Row_number() 
       OVER ( ORDER BY joiningdate ASC) AS Rownumber, 
      M.memberid, 
      P.name, 
      M.joiningdate 
     FROM tblmemberdata M 
      JOIN tblpersonaldetails P 
      ON M.memberid = P.memberid 
    ) 
    SELECT * 
    FROM Numbered 
    WHERE memberid = @MemberID