I have the following table
I have inserted Product B to it and it gives me an ID of 15
Then I have the definition table which is as follows.
I want to select the ProductDefinition rows where ProdID = 14 and replicate the same and insert it for ProdID = 15 like the following
How to achieve this using SQL code?
This will work with any column you choose. Not just primary key/ID.
The
xxx
is your new ProdID and theyyy
is your old one. This also assumes thatDefID
is automagically populated onINSERT
.Do you use Oracle? It does not have an automatic PK_generator, nothing to work for your
INSERT
silently. However, it has SEQUENCEs, so let's use itsNEXTVAL
:The INSERT operation is exactly the case for them, the purpose of a
SEQUENCE
, you just have to use it explicitly. More described: Managing Sequences # Using SequencesThe node for Sequences is on the level of Tables, i.e. in the SQLdeveloper. Ours are
ID_GENERATOR
, in every DB.Can use
MERGE
on SQL Server 2008, has the advantage of usingOUTPUT
to return theDefID
values, assuming they are auto-generated e.g.if you want to select all items (in condition the table not contains any primary keys)
in condition the table contains a primary keys, select only the columns that not primary key Like:
If you want to replicate data in same table use this logic:
first, insert statment where you want to insert...
second, select statment from where you want to take data for insertion....
now set filter which rows you want to duplicate
as want to replicate same data for different customers i have used this query.