问题描述
简化来源pl_sql是
select t.*,staff_no||'-'||rownum as pk
from (select * from hrmmgr.posting where type not in ('X','C') order by staff_no,postingdate) t;
我尝试将其重写为在sql server中运行
select t.*,staff_no + '-' + t.rownum as pk
from (select row_number() over (order by staff_no,postingdate) as rownum,*
from posting where type not in ('X',postingdate) t
但是出错
ORDER BY子句在派生的视图,内联函数中无效 表,子查询和公用表表达式,除非TOP,OFFSET 或还指定了FOR XML。
返回。
select t.*,postingdate OFFSET 0 ROWS) as rownum,postingdate) t
“ ROWS”附近的语法不正确。
解决方法
子查询中的ORDER BY
子句似乎是问题所在,SQL Server告诉您ORDER BY
在不使用TOP
之类的子查询中就无法出现。但是,这里甚至没有必要,因为您对ROW_NUMBER
的调用已经指定了在分配行号时要使用的ORDER BY
子句。试试这个版本:
SELECT t.*,staff_no + '-' + t.rownum AS pk
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY staff_no,postingdate) AS rownum,*
FROM posting
WHERE type NOT IN ('X','C')
) t;