使用有序结果填充表变量

时间:2017-02-16 15:18:35

标签: sql sql-server tsql

我想用CADEPA表的结果填充表变量。唯一的问题是必须订购这些结果。

我收到的错误是:

  

ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。

查询是:

DECLARE @DEPARTMENTS_TBL TABLE
(
    DEPA_KEY INT                
)

INSERT INTO @DEPARTMENTS_TBL(DEPA_KEY)
SELECT DEPA_KEY
FROM (
    SELECT DISTINCT DEPA_KEY
    FROM CADEPA
    WHERE DEPA_STA = '1'
    ORDER BY DEPA_NME
) P

2 个答案:

答案 0 :(得分:1)

表表示无序集。要做你想做的事,你需要一把钥匙来代表订单:

DECLARE @DEPARTMENTS_TBL TABLE (
     ID IDENTITY(1, 1) PRIMARY KEY
     DEPA_KEY INT                
);

INSERT INTO @DEPARTMENTS_TBL (DEPA_KEY)
    SELECT DEPA_KEY
    FROM CADEPA
    WHERE DEPA_STA = '1'
    GROUP BY DEPA_KEY
    ORDER BY MAX(DEPA_NME);

我还认为您应该在表格中加入DEPA_NME,但id列会保留排序。

请务必使用order by查询:

select d.*
from DEPARTMENTS_TBL d
order by id;

答案 1 :(得分:1)

在表别名(P)之后移动order by子句

INSERT INTO @DEPARTMENTS_TBL(DEPA_KEY)
SELECT DISTINCT  DEPA_KEY
FROM (
    SELECT DEPA_KEY, DEPA_NME
    FROM CADEPA
    WHERE DEPA_STA = '1'
) P
ORDER BY DEPA_NME