查询语法无效

时间:2014-08-12 19:23:47

标签: sql sql-server

我有一个类似的查询:SELECT TOP 20 a.Job_No FROM dbo.ScheduledatesFF这给了我前20个结果,但我想从20开始获得20个结果,我该如何设置偏移?

我试过:在查询结束时使用OFFSET 20,我收到了这个错误:

Incorrect syntax near 'OFFSET'

我在mysql中知道它的Offset,它在SQL中有什么不同吗?

这给了我一个错误:

SELECT 
    a.Job_No 
FROM (
    SELECT 
        ROW_NUMBER() OVER (ORDER BY a.Job_No) as RowNum 
    FROM dbo.ScheduledatesFF 
    FROM dbo.ScheduledatesFF AS a 
    INNER JOIN dbo.tblCustomers AS c 
        ON a.Job_No = c.Job_No 
    INNER JOIN dbo.scheduledatesSS AS z 
        ON a.Job_No = z.Job_No 
    LEFT OUTER JOIN dbo.maxscheddate AS m 
        ON a.Job_No = m.Job_No
        ) AS MyDerivedTable 
WHERE MyDerivedTable.RowNum BETWEEN 0 AND 20

Incorrect syntax near the keyword 'FROM'.

这是我最接近的:

SELECT a.Job_No, ROW_NUMBER() OVER (ORDER BY a.Job_No) as datacounter FROM dbo.ScheduledatesFF AS a INNER JOIN dbo.tblCustomers AS c ON a.Job_No = c.Job_No INNER JOIN dbo.scheduledatesSS AS z ON a.Job_No = z.Job_No LEFT OUTER JOIN dbo.maxscheddate AS m ON a.Job_No = m.Job_No

但在datacounter的where子句中它表示它不存在

2 个答案:

答案 0 :(得分:3)

查看您发布问题的代码很简单。你有两个" FROM dbo.ScheduledatesFF"' s

请参阅。

SELECT 
    MyDerivedTable.Job_No 
FROM (
    SELECT 
        a.Jon_No,
        ROW_NUMBER() OVER (ORDER BY a.Job_No) as RowNum 
    FROM dbo.ScheduledatesFF --<--What's up with this guy here?
    FROM dbo.ScheduledatesFF AS a 
    INNER JOIN dbo.tblCustomers AS c 
        ON a.Job_No = c.Job_No 
    INNER JOIN dbo.scheduledatesSS AS z 
        ON a.Job_No = z.Job_No 
    LEFT OUTER JOIN dbo.maxscheddate AS m 
        ON a.Job_No = m.Job_No
        ) AS MyDerivedTable 
WHERE MyDerivedTable.RowNum BETWEEN 0 AND 20

仍然认为下面的解决方案是优越的,但这就是你得到语法错误的原因。

答案 1 :(得分:1)

看看这里:Row Offset in SQL Server看起来似乎没有直接的等效关键字,但是通过一些解决方法仍然可以实现相同的效果。

SELECT Job_No
FROM (
SELECT Job_No, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow

@startRow@endRow替换为您的起始行号和结束行号。

更新:根据问题中的更新信息:

 SELECT 
 Job_No 
 FROM (
 SELECT 
 ROW_NUMBER() OVER (ORDER BY a.Job_No) as RowNum 
 FROM dbo.ScheduledatesFF AS a 
 INNER JOIN dbo.tblCustomers AS c 
 ON a.Job_No = c.Job_No 
 INNER JOIN dbo.scheduledatesSS AS z 
 ON a.Job_No = z.Job_No 
 LEFT OUTER JOIN dbo.maxscheddate AS m 
 ON a.Job_No = m.Job_No
 ) AS MyDerivedTable 
 WHERE MyDerivedTable.RowNum BETWEEN 0 AND 20

无论如何,这是我最好的猜测。看起来你有两个来自背靠背的陈述......