i have two tables:
new_table
id | parentid | f1 | f2 | customerid
initial_table (does not have customerid)
id | parentid | f1 | f2
what i need to do is move ALL items from initial_table to new_table. however, id’s change (auto generated) in the new_table!
—
so, my idea (for now) is:
1 – move all data except id and parentid from initial_table to new_table
2 – use a lookup_table with
id | originalparentid | newparentid | customerid
3 – go through the lookup_table and update the new_table parentid column with the new parentid‘s
—
so…
question – 1 – is this the right way?
question – 2a – if yes, how to do it?
question – 2b – if no, how then?
the problem in 2 is that i am doing this from a trigger and customerid is SELECT @customerid = id FROM inserted and this is fine. then i am doing
INSERT INTO new_table (f1, f2, customerid)
SELECT f1, f2 @customerid FROM initial_table
but i don’t get the new id’s from new_table when i do it like that.
—
so, please, help me write this trigger:
i need to copy all data from initial_table to new_table with the problem that the id’s will change and i need to update the parentid’s accordingly in the new_table
thnx
—
here is my current trigger:
ALTER TRIGGER Copy
ON dbo.Customers
FOR INSERT
AS
BEGIN TRANSACTION
/* variables */
DECLARE
@customerid bigint
SELECT @customerid = id FROM inserted
/* insert all for this customer */
INSERT INTO new_table (f1, f2, customerid)
SELECT f1, f2 @customerid FROM initial_table
/* TODO: add entries to lookup table */
/* TODO: fix the pages' parentid's */
/* execute */
COMMIT TRANSACTION
GO
I would just turn
IDENTITY INSERToff for the initial insert and avoid this whole mess. Is there any reason you can’t do that? Something like this should do it:Then when you are done just run