简体   繁体   English

根据现有行将行插入SQL表

[英]Insert row into SQL table based on existing row

I need to add a new row to a table in Oracle. 我需要在Oracle中向表中添加一个新行。 The problem is that the table has 50 columns and I really don't want to write them all out for an INSERT statement. 问题是该表有50列,我真的不想为INSERT语句全部写出来。 I tried to do a SELECT INTO statement to duplicate the row and then change the fields I care about individually, but this results in a UNIQUE violation on the primary key. 我尝试执行SELECT INTO语句来复制行,然后单独更改我关心的字段,但这会导致主键上出现UNIQUE冲突。 So what I really want to do is declare a variable that holds one row without naming all the columns, change the primary key field, and then insert that variable. 所以我真正想做的是声明一个变量,它保存一行而不命名所有列,更改主键字段,然后插入该变量。 How do? 怎么办?

You can use %ROWTYPE in an anonymous PL/SQL block to declare a record representing a row from a table and then select a row into that record and change the primary key and insert the updated record. 您可以在匿名PL / SQL块中使用%ROWTYPE来声明表示表中行的记录,然后在该记录中选择一行并更改主键并插入更新的记录。 You can even re-use it for multiple inserts: 您甚至可以将其重复用于多个插入:

DECLARE
  rec SOME_TABLE%ROWTYPE;
BEGIN
  SELECT *
  INTO   rec
  FROM   SOME_TABLE
  WHERE  A = 1; -- Primary Key

  rec.A := 2; -- Change the primary key value.
  INSERT INTO SOME_TABLE VALUES rec;

  rec.A := 3; -- Change the primary key again.
  INSERT INTO SOME_TABLE VALUES rec;

  FOR i IN 4 .. 9 LOOP
    rec.A := i; -- Change it repeatedly...
    INSERT INTO SOME_TABLE VALUES rec;
  END LOOP;

  FOR i IN 1 .. 3 LOOP
    rec.A := SOME_SEQUENCE.NEXTVAL; -- Or you can manage the primary key's value using a sequence.
    INSERT INTO SOME_TABLE VALUES rec;
  END LOOP;
END;
/

SQLFIDDLE SQLFIDDLE

I have often wanted to do something similar to this, but it's just not possible in any SQL variant I know of. 我经常想做类似的事情,但在我所知道的任何SQL变体中都是不可能的。 You cannot ask for only some of the columns in a table without explicitly naming them (or perhaps defining a view on them in advance). 如果没有明确地命名它们(或者可能事先在它们上定义视图),您不能只询问表中的某些列。

The only shortcut I can suggest is to dump the list of column names into a convenient location and then just copy it into an insert statement, changing only the value you need: 我可以建议的唯一捷径是将列名列表转储到方便的位置,然后将其复制到insert语句中,只更改所需的值:

insert into foo (select 'newC1' as c1, c2, c3, c4, ..., c50 from foo where bar='baz');

::edit:: In fact, I do this so often that I wrote a Python script to help me. :: edit ::事实上,我经常这样做,所以我写了一个Python脚本来帮助我。 I tell it what table I'm editing, some where clause that matches exactly 1 row, the list of column(s) I want to change, and the list of new value(s) I want in those columns. 我告诉它我正在编辑什么表,一些where子句恰好匹配1行,我想要更改的列列表,以及我想要在这些列中的新值列表。 Then it does the rest. 然后它完成剩下的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM