0

I'm trying to write an SQL query but when I try to save it throws me an incorrect syntax error. Here's the query:

(
@top int,
@bottom int
)

AS
        SELECT *
        FROM (SELECT top (@bottom - @top + 1) *
            FROM (SELECT top (@bottom) *
                  FROM    tblPlayers INNER JOIN
                          tblPosition ON tblPlayers.IDPosition = tblPosition.IDPosition INNER JOIN
                          tblTeams ON tblPlayers.IDTeam = tblTeams.IDTeam
                  ORDER BY (PPG DESC, APG DESC, RPG DESC)
                 )
            ORDER BY PPG ASC, APG ASC, RPG ASC
             )      
        ORDER BY PPG DESC, APG DESC, RPG DESC
    RETURN

The problem is with the most inner ORDER BY. Without it's brackets it gives an incorrect syntax near the keyword 'ORDER'. With the brackets the error is incorrect syntax near the keyword 'DESC'. I'm out of ideas. The syntax seems fine to me. Thanks in advance.

2
  • PLease tell us what concrete database you're using - use the oracle, mysql, postgresql, sql-server tags - or specify what else you're using (SQL is just the query language - not a product). ALso - this is not a complete code snippet - is this the body of a stored procedure? Of a CTE? Please post something complete - not just a few lines out of the middle of something....
    – marc_s
    May 18, 2014 at 13:32
  • I added the sql-server tag because the syntax looks like SQL Server. May 18, 2014 at 13:34

1 Answer 1

0

Your query needs table aliases, which may be part or all of the problem. In addition, you should list the columns explicitly in the innermost subquery, because there are duplicate names:

    SELECT t.*
    FROM (SELECT top (@bottom - @top + 1) t.*
        FROM (SELECT top (@bottom) co1, col2, col3, . . .
              FROM    tblPlayers INNER JOIN
                      tblPosition ON tblPlayers.IDPosition = tblPosition.IDPosition INNER JOIN
                      tblTeams ON tblPlayers.IDTeam = tblTeams.IDTeam
              ORDER BY PPG DESC, APG DESC, RPG DESC
             ) t
        ORDER BY PPG ASC, APG ASC, RPG ASC
         ) t   
    ORDER BY PPG DESC, APG DESC, RPG DESC
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.