Oracle 11g:将一列从一个表复制到另一个表,并添加序列ID。删除序列

时间:2018-06-26 12:53:02

标签: sql oracle11g

我想将列值从一个表复制到另一个表中,但操作类似(不起作用):

create sequence INSTITUTION_SEQ
minvalue 1
maxvalue 999999999999999999999
start with 1
increment by 1
cache 20;

INSERT INTO INSTITUTION 
(ID, NAME)
VALUES(
INSTITUTION_SEQ.nextval, 
SELECT DISTINCT ACB_BANK_NAME FROM LUP ORDER BY ACB_BANK_NAME
);

问题

  1. 为了获得预期的结果,要启动什么正确的SQL查询?
  2. 如何在脚本末尾删除该序列?尝试过DROP INSTITUTION_SEQ但导致了ORA-00950: invalid DROP option

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法获取序列值,而不是创建/使用/删除序列:

INSERT INTO INSTITUTION (ID, NAME)
SELECT ROW_NUMBER() OVER (ORDER BY ACB_BANK_NAME), ACB_BANK_NAME 
FROM
 ( -- DISTINCT is processed after ROW_NUMBER
   SELECT DISTINCT ACB_BANK_NAME FROM LUP
 ) dt;

INSERT INTO INSTITUTION (ID, NAME)
SELECT ROW_NUMBER() OVER (ORDER BY ACB_BANK_NAME), ACB_BANK_NAME 
FROM LUP
GROUP BY ACB_BANK_NAME; -- GROUP BY is processed before ROW_NUMBER

答案 1 :(得分:2)

您无需创建和删除序列,可以使用rownum或分析函数:

INSERT INTO INSTITUTION (ID, NAME)
SELECT rownum, ACB_BANK_NAME
FROM (
  SELECT DISTINCT ACB_BANK_NAME FROM LUP ORDER BY ACB_BANK_NAME
);