我想使用union ALL从select语句插入

时间:2011-11-30 09:45:13

标签: sql database oracle

我希望在表中插入记录时对查询使用union。插入也具有一些硬编码值。其余的价值观来自工会。 例如..

INSERT INTO my_test_one (name, sirname, Dept)
VALUES
  ((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 ));

4 个答案:

答案 0 :(得分:4)

尝试:

INSERT INTO my_test_one (name, sirname, Dept) 
(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 );

希望它有所帮助...

答案 1 :(得分:2)

我认为你这里不需要VALUES。 (INSERT INTO ... ( ... ) SELECT ...

答案 2 :(得分:1)

为什么不使用两个插入而不是使用union all?

INSERT INTO my_test_one (name, sirname, Dept)
SELECT 'name1','sirname1', Dept FROM my_test_one_backup WHERE dept = 500;

INSERT INTO my_test_one (name, sirname, Dept)
SELECT 'name1','sirname1', Dept FROM my_test_one_backup WHERE dept = 501;

INSERT INTO my_test_one (name, sirname, Dept)
SELECT 'name1','sirname1', Dept FROM my_test_one_backup WHERE dept in (500,501);

答案 3 :(得分:0)

你可以这样做:

如果表格不存在,您可以使用:

SELECT 'name1' [name],'sirname1' [sirname], Dept INTO my_test_one 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 (name, sirname, Dept)
SELECT 'name1','sirname1', Dept FROM my_test_one_backup WHERE dept in (500,501)