【问题标题】:Why no parentheses on this cursor declaration?为什么这个游标声明上没有括号?
【发布时间】:2015-03-03 01:30:26
【问题描述】:

我在这里有一个游标声明:

declare c cursor
for     (select ProductName, ListPrice
        from Products
        where ListPrice > 700)

但是如果我添加一个order by 子句,我会得到一个错误:

declare c cursor
for     (select ProductName, ListPrice
        from Products
        where ListPrice > 700
        order by ListPrice desc)

错误:Incorrect syntax near the keyword 'order'.

但是如果我去掉括号,错误就会消失:

declare c cursor
for     select ProductName, ListPrice
        from Products
        where ListPrice > 700
        order by ListPrice desc

也许我有点不清楚括号在 SQL Server 中的作用。是什么赋予了?为什么order by 子句会以这种方式与括号交互?

【问题讨论】:

  • SQL Server 不喜欢子查询中的order by(除非您也有top)。我猜它会将括号内的查询解释为子查询,因为不需要括号。
  • 这是有道理的。你应该把它放在一个答案中,这样我就可以给你信用了。

标签: sql sql-server-2012 syntax-error cursors


【解决方案1】:

order by 不允许在子查询中使用,如 cmets 中所述。将 select 括在括号中会使 SQL 将其解释为子查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    相关资源
    最近更新 更多