开发者

Why does this "paging" query throw a "does not match with a table name or alias" error?

开发者 https://www.devze.com 2023-04-01 11:20 出处:网络
Warning, \"ugly\" query alert (MS SQL Server 2008): SELECT BaseDocs.* FROM ( SELECT ROW_NUMBER() OVER (ORDER BY BaseDocs.DateUpdated DESC) AS Row, BaseDocs.*

Warning, "ugly" query alert (MS SQL Server 2008):

SELECT BaseDocs.* FROM (
  SELECT ROW_NUMBER() OVER (ORDER BY BaseDocs.DateUpdated DESC) AS Row, BaseDocs.* 
    FROM BaseDocs INNER JOIN DocCats ON BaseDocs.DocId = DocCats.DocId  
    WHERE DocCats.CatId IN (4) AND BaseDocs.BaseId = 1
  ) AS开发者_StackOverflow社区 Paged 
  WHERE Row > 0 AND Row <=3

This query throws this error:

The column prefix 'BaseDocs' does not match with a table name or alias name used in the query.

This query is against these tables:

BaseDocs Table
 - DocId PK
 - BaseId FK
 - ...

DocCategories Table
 - CatId PK
 - ...

DocCats (join) Table
 - DocId FK PK 
 - CatId FK PK

After "hacking" at this query for so long, I think my brain is frying... but it's close, I can feel it. Thanks in advance!


Just don't specify a table alias in your SELECT - that table alias is visible only inside your subquery!

SELECT *
FROM 
   (SELECT 
        ROW_NUMBER() OVER (ORDER BY BaseDocs.DateUpdated DESC) AS Row, 
        BaseDocs.* 
    FROM BaseDocs 
    INNER JOIN DocCats ON BaseDocs.DocId = DocCats.DocId  
    WHERE 
         DocCats.CatId IN (4) 
         AND BaseDocs.BaseId = 1
  ) AS Paged 
WHERE 
   Row > 0 AND Row <= 3

or alternatively: use the alias given to your subquery:

SELECT Paged.* .....
0

精彩评论

暂无评论...
验证码 换一张
取 消