tags:

views:

63

answers:

3

hello,

I have two schemas S1 and S2 with identical table structure. I`ll start with example:

on S1.table1 I have:

ID   DATA1       DATA2


01   data1       test1
02   data1       test1

on S2.table1 I have:

 ID   DATA1       DATA2


01   data2       test2
02   data2       test2

Is it possible to select one row (from S1.table1) update it (change value of ID column) and insert it into S2.table1? I want to write single SQL query which will be used as prepared statement (Java).

Final result on S2 should be:

 ID   DATA1       DATA2


01   data2       test2
02   data2       test2
03   data1       test1

so i inserted first row from S1.table1, and changed only ID.

Thanks, Jonas

+2  A: 

How about

INSERT INTO S2
SELECT 03, DATA1, DATA2 FROM S1 WHERE ID=01

That is, you just select the data you want, but explicitly indicate any replacement data.

JacobM
Thanks, great idea.But, what if i do NOT want to list all other columns? it`s like:INSERT INTO S2.table1 (SELECT * FROM S1 Where ID = 01)but i want to modify the ID column (it is not autogenerated)
Maciulis
Yeah, that's a tough one. I've also had occasions where I've wanted a SELECT EVERYTHING EXCEPT command, but there isn't one. I guess you could simply copy the entire row, and then immediately do an update.
JacobM
+1  A: 
INSERT INTO S2 (Data1, Data2) SELECT Data1, Data2 FROM S1 WHERE ID=xxx

Assuming the ID in S2 is autoincremented (via sequence and trigger for instance).

Lucero
Use [sequence name].NEXTVAL - there usually isn't a need to do this within a trigger.
OMG Ponies
True, but the trigger has the advantage of not requiring you to use the correct sequence. I guess it's a matter of taste.
Lucero
The ID column is not autoincremented, I used very simplified example, the table actually contains about 50 columns, and the key column (constraint unique) is not auto generated value.
Maciulis
OMG Ponies
@Lucero: Dealing with the sequence within a trigger is overcomplication...
OMG Ponies
+1  A: 

You must use a sequence:

insert into s2.table1
select seq.next_val, data1, data2
from s1.table1

The sequence will always count up. So when you run this again, the new rows will be "appended" to the existing ones.

Aaron Digulla