Update result set values in a column on insert

时间:2018-09-18 20:00:53

标签: sql oracle sql-insert

I'm sure this is a basic SQL syntax step that I'm forgetting, but I can't seem to recall how to complete this.

I'm basically performing an INSERT into a table by using the results of a sub-query from the same table. However, when the data is inserted, I want to change the value of a Business Unit number. Basically, I'm trying to copy the settings of an existing Business Unit to a new Business Unit (that doesn't have records in this table yet) in the same table. On the insert, I need to change the values of the result set to insert the new business unit.

For example, suppose I have a table named 'dogs' with columns dogID, dogName, dogBreed, dogUnit. I know I can do an insert like this:

INSERT INTO dogs (dogID, dogName, dogBreed, dogUnit) VALUES (
'005','Test','M','1550');

And it will work.

But I could also perform an insert using a select:

INSERT INTO dogs (dogID, dogName, dogGender, dogUnit)
SELECT dogID, dogName, dogGender, dogUnit FROM dogs WHERE dogunit = '1550'

And this will work but it will definitely insert duplicate records. What I'm trying to actually do is (using plain English in the last line):

INSERT INTO dogs (dogID, dogName, dogGender, dogUnit)
SELECT dogID, dogName, dogGender, dogUnit FROM dogs WHERE dogunit = '1550'
BUT change dogUnit to '1660' on insert

Is this possible or am I thinking about this process incorrectly? Thanks in advance for any assistance. My next thought was to basically insert the results of the query into a temp table, update the unit # in every record in the temp table, and then copy the newly updated result set back to the other table.

1 个答案:

答案 0 :(得分:2)

Just replace the value when selecting it:

INSERT INTO dogs (dogID, dogName, dogGender, dogUnit)
SELECT dogID, dogName, dogGender, '1660' FROM dogs WHERE dogunit = '1550'