多行插入plsql ora 01427

时间:2016-04-24 00:27:39

标签: sql oracle insert

http://i.stack.imgur.com/t2tMi.jpg

SELECT T.USER_ID
  FROM USER_OTHER_PRIVILEGES T
 WHERE T.UOPM_ID = 17
   AND T.PRIV_ID IN (719) ;  67 rows selected

INSERT INTO  USER_OTHER_PRIVILEGES (
  ID, PRIV_ID,UOPM_ID,USER_ID,ML_ID,PARENT_ID
) VALUES (
  PRIV_USER_OTH_ID_SEQ.NEXTVAL,
  1792,
  17,
  ( SELECT T.USER_ID
    FROM   USER_OTHER_PRIVILEGES T
           JOIN USERS U
           ON U.ID = T.USER_ID
    WHERE  T.UOPM_ID = 17
    AND    T.PRIV_ID IN (719) ),
  NULL,
  1
)

2 个答案:

答案 0 :(得分:1)

错误表示该子查询:

SELECT T.USER_ID
    FROM   USER_OTHER_PRIVILEGES T
           JOIN USERS U
           ON U.ID = T.USER_ID
    WHERE  T.UOPM_ID = 17
    AND    T.PRIV_ID IN (719)

返回多一行。
请运行此查询,您将看到至少会显示2个用户ID。

带有VALUE子句的INSERT语句只能在表中插入一行,并且它只需要VALUES子句中每列的一个值:

INSERT INTO table( col1, col2, col3 ) VALUES ( val1, val2, val3 )

您无法在行中的一列输入多个值。

例如,如果此子查询返回三个数字:1,2,3,则不能以这种方式插入一行:

+------+---------+---------+---------+-------+-----------+
| ID   | PRIV_ID | UOPM_ID | USER_ID | ML_ID | PARENT_ID | 
+------+---------+---------+---------+-------+-----------+
| 456  |    1792 |      17 |  1,2,3  |  NULL |         1 |
+------+---------+---------+---------+-------+-----------+

我想你不想只插入一行,但是你要为suquery返回的每个条目插入一个单独的行,如下所示:

+------+---------+---------+---------+-------+-----------+
| ID   | PRIV_ID | UOPM_ID | USER_ID | ML_ID | PARENT_ID | 
+------+---------+---------+---------+-------+-----------+
| 456  |    1792 |      17 |      1  |  NULL |         1 |
+------+---------+---------+---------+-------+-----------+
| 457  |    1792 |      17 |      2  |  NULL |         1 |
+------+---------+---------+---------+-------+-----------+
| 458  |    1792 |      17 |      3  |  NULL |         1 |
+------+---------+---------+---------+-------+-----------+

在这种情况下,您无法使用INSERT INTO ... VALUES ...语法,您需要使用INSERT INTO .... subquery变体, 有关详细信息,请参阅此答案:How can I insert values into a table, using a subquery with more than one result?

您对此类案例的插入声明可以是:

INSERT INTO  USER_OTHER_PRIVILEGES (
  ID, PRIV_ID,UOPM_ID,USER_ID,ML_ID,PARENT_ID
) 
SELECT
     PRIV_USER_OTH_ID_SEQ.NEXTVAL,
     1792,
     17,
     T.USER_ID,
     NULL,
     1
FROM USER_OTHER_PRIVILEGES T
JOIN USERS U
ON U.ID = T.USER_ID
WHERE  T.UOPM_ID = 17
  AND  T.PRIV_ID IN (719) 

答案 1 :(得分:0)

回答,谢谢:)

DECLARE

v_USER_ID INTEGER;


BEGIN
  FOR XYZ IN 
              (
                SELECT T.USER_ID
                FROM   USER_OTHER_PRIVILEGES T
                JOIN USERS U
                ON U.ID = T.USER_ID
                WHERE  T.UOPM_ID = 17
                AND    T.PRIV_ID IN (719)
              )
  LOOP
  v_USER_ID:= XYZ.USER_ID;

                INSERT INTO  USER_OTHER_PRIVILEGES
                (ID, PRIV_ID,UOPM_ID,USER_ID,ML_ID,PARENT_ID)
                VALUES
                (PRIV_USER_OTH_ID_SEQ.NEXTVAL,1792, 17,v_USER_ID, NULL,1);

                COMMIT;

  END LOOP;

END;