我想使用union all进行插入,其中有一列从序列中获取值

时间:2011-11-30 13:53:31

标签: sql database oracle plsql

我试过

INSERT INTO my_test_one (rollno,name, sirname, Dept) 
(select rollno_seq.nextval,'name1','sirname1', Dept 
   FROM my_test_one_backup 
  WHERE dept = 500      
UNION ALL
 select rollno_seq.nextval,'name1','sirname1', Dept 
   FROM my_test_one_backup 
  WHERE dept = 501 );

执行此操作时,我收到错误

错误报告:

  

SQL错误:ORA-02287:此处不允许序列号
  02287. 00000 - “此处不允许使用序列号”

3 个答案:

答案 0 :(得分:4)

在这种情况下,请勿使用UNION,而应使用SELECTOR

SELECT rollno_seq.nextval,'name1','sirname1', Dept 
FROM my_test_one_backup 
WHERE dept = 500 OR dept = 501

答案 1 :(得分:3)

尝试:

INSERT INTO my_test_one 
(rollno, name, sirname, Dept)  
SELECT rollno_seq.nextval,
       name1,
       sirname1,
       dept
  FROM (select 'name1' as name1,'sirname1' as sirname1, Dept
         FROM my_test_one_backup    
        WHERE dept = 500       
       UNION ALL  
       select 'name1','sirname1', Dept     
         FROM my_test_one_backup    
        WHERE dept = 501 ); 

编辑:更好的是,使用CodeBrickie所说的ORIN语句。

WHERE dept IN (500, 501);

Edit2:

目前您选择'name1','sirname1'作为文字,因此返回的每一行都会插入下一个序列号,'name1','sirname1'以及DEPT列的值。

如果你的表有名为name1和sirname1的列,那么你需要删除单引号(你也不需要列别名),例如:

INSERT INTO my_test_one 
(rollno, name, sirname, Dept)  
SELECT rollno_seq.nextval,
       name1,
       sirname1,
       dept
  FROM (select name1, sirname1, Dept
         FROM my_test_one_backup    
        WHERE dept = 500       
       UNION ALL  
       select name1, sirname1, Dept     
         FROM my_test_one_backup    
        WHERE dept = 501 ); 

或者

INSERT INTO my_test_one 
(rollno, name, sirname, Dept)  
SELECT rollno_seq.nextval,
       name1,
       sirname1,
       dept
  FROM my_test_one_backup
 WHERE dept IN (500, 501);

答案 2 :(得分:2)

您不能在联合选择中使用序列,因此您需要将联合放在子查询中并将序列放在外部查询中:

INSERT INTO my_test_one (rollno,name, sirname, Dept) 
select rollno_seq.nextval, name1, sirname1, dept
  from (SELECT 'name1' as name1,'sirname1' as sirname1, Dept 
          FROM my_test_one_backup 
         WHERE dept = 500      
         UNION ALL
        SELECT 'name1','sirname1', Dept 
          FROM my_test_one_backup 
         WHERE dept = 501 );

您还应注意,在SQL中,双引号表示对象名称,单引号表示字符串,因此'name1''sirname1'将是静态字符串,而不是列引用。