简体   繁体   English

Oracle SQL将行插入另一个表并更新数据

[英]Oracle sql insert row into another table and update data

In Oracle sql I can select a row into another table 在Oracle SQL中,我可以选择另一表中的一行

insert into TableA (select * from TableB b where b.id = 2);

however, b.color = 'blue' and I want to update it to red before the row gets inserted into TableA without having to select each column from TableB, I want to select *. 但是,b.color ='blue'并且我想在将行插入TableA之前将其更新为红色,而不必从TableB中选择每一列,我想选择*。

Please do not mark this as answered in another question and give a link to answer that I can not use. 请不要将此标记为在其他问题中已回答,并提供指向我无法使用的答案的链接。 TableA does not have an id that matches TableB. TableA没有与TableB匹配的ID。

Thank you 谢谢

Insert your select into a temp table (which you will have to create) then update your temp table to red then insert it back to A 将您的选择插入到临时表(必须创建)中,然后将临时表更新为红色,然后将其重新插入到A中

  INSERT INTO TEMP_TABLE 
  Select * from TableB b where b.id = 2

  Update temp_table
  Set color = 'Red'

  Insert into TableA (Select * from Temp_table)

"I want to select *" “我要选择*”

does not make sense because you do NOT want to select *. 没有意义,因为您不想选择*。 If you did then you would want red not blue as the color. 如果这样做了,那么您会希望红色而不是蓝色。

You can hack around this using a trigger, eg 您可以使用触发器来解决这个问题,例如

trigger BLAH 
before insert on A
for each row
begin
  :new.color := case when :new.color = 'blue' then 'red' else :new.color end;
end;

but man..I cannot tell you what a bad bad idea that would be. 但是人..我不能告诉你这是一个坏主意。

I would suggest: 我会建议:

insert into TableA(col1, . . . , color, . . . coln)
     select . . . , (case when color = 'blue' then 'red' else color end), . . .
     from TableB b
     where b.id = 2;

Whether you like it or not, it is best practice to list all the columns both for the insert and the select , particularly for code that may be run more than one time. 无论您是否喜欢,最好的做法是列出insertselect所有列,尤其是对于可能运行多次的代码。

If you find it too hard to list out the columns (using either a spreadsheet or SQL query), you can do the update afterwards : 如果发现列出列太困难(使用电子表格或SQL查询),则可以在以后进行更新:

insert into TableA
     select *
     from TableB b
     where b.id = 2;

update TableA
    set color = 'red'
    where color = 'blue' and id = 2;

This is approximate, because you might already have rows in the table, but it gives an idea. 这是近似值,因为表中可能已经有行,但是可以提供一个思路。

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

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