如何在INNER JOIN中使用SQL ROW_NUMBER?

时间:2014-02-12 15:58:32

标签: sql sql-server tsql

我已编写此查询以获取特殊关键字的数据:

ALTER procedure [dbo].[GetAllSpecialPaperTags]
    @PKeyword nvarchar(200)
as
begin
   select 
      Papers.PID, Papers.PTitle, Papers.PaperSummary 
  from 
      PaperKeywords 
  left join 
      PaperTags on PaperKeywords.PKeyID = PaperTags.PKeyID
  left join 
      Papers on PaperTags.PID = Papers.PID 
  where 
      PaperKeywords.PKeyword = @PKeyword
end

我想将此文章用于自定义分页:Custom Paging using SQL Server Stored Procedure

我写了这个查询,但是我收到了一个错误:

create procedure [dbo].[GetAllSpecialPaperTags]
   @PageIndex INT = 1
   ,@PageSize INT = 10
   ,@RecordCount INT OUTPUT
   ,@PKeyword nvarchar(200)
as
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
      (
            ORDER BY [Papers.PID] ASC
      )AS RowNumber
    ,Papers.PID , Papers.PTitle , Papers.PaperSummary
     INTO #Results
      from PaperKeywords 
        left join PaperTags on PaperKeywords.PKeyID = PaperTags.PKeyID
        left join Papers on PaperTags.PID = Papers.PID where PaperKeywords.PKeyword = @PKeyword

      SELECT @RecordCount = COUNT(*)
      FROM #Results

      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1

      DROP TABLE #Results
end

错误:

  

Msg 207,Level 16,State 1,Procedure GetAllSpecialPaperTags,Line 11
  列名称“Papers.PID”无效。

为什么?

1 个答案:

答案 0 :(得分:3)

这是您的order by表达式:

        ORDER BY [Papers.PID] ASC

正在寻找一个完整名称为“Papers.PID”的列。 正在寻找PID中的Papers列。只需放下牙箍:

        ORDER BY Papers.PID ASC