I would like to vertically split an existing (already filled with data).
Say my starting table (trip
) looks like this:
ID Person Age Trip_to Date
... Alice 21 Los Angeles 2015-04-01
... Bob 35 New York 2015-03-15
... Bob 35 Chicago 2015-03-20
... Bob 35 San Francisco 2015-03-29
... Carol 29 Miami 2015-03-30
... Carol 29 Boston 2015-04-05
I would like to split this table into two tables, as it should be, one each for person
and trip
.
When copying each unique person into a table person
, I want the automatically created uniqueidentifier
column in that table person.pId
(the primary key) to be copied into a newly created uniqueidentifier
column trip.personid
in the original table and turn that into a foreign key. (I would then delete the trip.person
and trip.age
column from the original table, and have the data structured as I want them.)
I thought I could use a trigger for that when I insert the person rows into the new table, like so:
CREATE TRIGGER tr_person
on person
after INSERT
as
begin
UPDATE Trip
SET personId=(SELECT i.pId from inserted i)
WHERE person=(SELECT i.person from inserted i) and age=(SELECT i.age from inserted i)
END
However, I get this:
Subquery returned more than 1 value.
This is not permitted when the subquery follows =, !=, <, <= , >, >=
or when the subquery is used as an expression.
Apparently the trigger only executes after all (potentially multiple!) inserts have been carried out, and by that time a query on inserted is no longer allowed for my SET
statement.
I also thought about using an OUTPUT
clause on the INSERT
statement, but that wouldn't work either
Insert into person (Driver, Age)
OUTPUT inserted.pId INTO trip.personId WHERE trip.person=inserted.person AND trip.Age=inserted.Age
(Select DISTINCT Person, Age FROM Trip)
So I am wondering now, am going about this all wrong? Is there another way to automagically create the keys and relationships between the two newly split tables?
EDIT Desired result: Table trip:
ID Trip_to Date PersonId
... Los Angeles 2015-04-01 xxxx1
... New York 2015-03-15 xxxx2
... Chicago 2015-03-20 xxxx2
... San Francisco 2015-03-29 xxxx2
... Miami 2015-03-30 xxxx3
... Boston 2015-04-05 xxxx3
Table person
pId Person Age
xxxx1 Alice 21
xxxx2 Bob 35
xxxx3 Carol 29
(The ID fields should all be uniqueidentifiers, of course)