使用带有别名和序列的asubselect插入子查询中的所有行

时间:2013-08-01 18:49:26

标签: sql oracle plsql plsqldeveloper

我在使用子查询插入表时遇到问题,并在具有序列的表上进行子选择。这是我的代码的简化版本:

 INSERT INTO my_table
     (sequence_id,
     product_code,
     product_status)
 SELECT 
     sequence_id.NEXTVAL,
     alias_table.* from (SELECT
     product_code, 
     product_status,
 FROM products
 WHERE product_code = '123456') alias_table;

我遇到的主要问题是序列,因为此查询将返回多行,我需要序列前进。任何帮助都非常感谢!

3 个答案:

答案 0 :(得分:0)

INSERT ...
SELECT 
 sequence_id.NEXTVAL,
 product_code, 
 product_status
FROM products
WHERE product_code = '123456';

答案 1 :(得分:0)

试试这个(我没试过)

INSERT INTO my_table
 (sequence_id,
 product_code,
 product_status)
 SELECT 
     sequence_id.NEXTVAL,
     alias_table.product_code,
     alias_table.product_status
 from (SELECT
           product_code, 
           product_status
       FROM products
       WHERE product_code = '123456') alias_table;

答案 2 :(得分:0)

创建一个触发器以插入下一个序列值:

CREATE OR REPLACE TRIGGER my_schema.my_table_ins_trg
   BEFORE INSERT ON my_schema.my_table FOR EACH ROW
   WHEN (New.ID IS NULL) 
BEGIN
  SELECT my_schema.sequence_id.Nextval INTO :New.ID FROM dual;
END;

然后您可以从插入查询中删除序列:

 INSERT INTO my_table
     (product_code,
      product_status)
 SELECT alias_table.* FROM (SELECT product_code, product_status
                              FROM products
                             WHERE product_code = '123456') alias_table;