使用“WITH”子句插入多行时出现顺序错误

时间:2013-04-29 12:47:32

标签: oracle sequence

  INSERT INTO items (
    item_id, psuedo_row_flag, item_hierarchy_level, 'some other cols...'  
  )
  WITH s_item_group
  AS 
    (
      SELECT hier_level, 'some other cols...'   FROM ITEM_GROUPS   
    )
    SELECT MY_SQL.nextval, 'N', hier_level FROM s_item_group
    UNION ALL
    SELECT MY_SQL.nextval, 'Y', hier_level + 1 FROM s_item_group;

基本上我想插入两组行。一个表示实际行,另一个表示伪行。伪行将有 psuedo_row_flag设置为'Y',其层次结构级别为其对应的实际行的hierarchy_level的+1。

当我尝试此查询时,我收到错误“此处不允许序列号”

3 个答案:

答案 0 :(得分:2)

将UNION ALL包装在另一个子查询中:

 INSERT INTO items
   (item_id,
    psuedo_row_flag,
    item_hierarchy_level)
   WITH s_item_group AS
    (SELECT hier_level
       FROM ITEM_GROUPS)
   select my_sql.nextval as item_id,
          psuedo_row_flag,
          hier_level
     from (SELECT 'N' psuedo_row_flag,
                  hier_level
             FROM s_item_group
           UNION ALL
           SELECT 'Y' psuedo_row_flag,
                  hier_level + 1
             FROM s_item_group)

顺便说一下,你可能想要修复psuedo_row_flag的拼写: - )

答案 1 :(得分:2)

您无法在UNION'ed查询中使用序列。

试试这个:

INSERT
INTO    items
WITH    s_items_group AS (...)
SELECT  my_sql.nextval, flag, hier_level
FROM    (
        SELECT  'N' flag, hier_level
        FROM    s_items_group
        UNION ALL
        SELECT  'Y' flag, hier_level + 1
        FROM    s_items_group
        )

答案 2 :(得分:0)

对于这种情况,如果要为查询中投射的每一行插入两行,请查看使用多表插入。序列有点问题,但您可以使用触发器填充该列。