I have following code in my SQL Server 2008 R2 stored procedure. In that stored procedure, I am copying one city to another city with it's family and persons.
Here I maintain family's source and target id in @FamilyIdMap
.
left column indicates the codes line no.
-- Copy Person
1> DECLARE @PersonIdMap table (TargetId int, SourceId int)
2> MERGE Person as PersonTargetTable
3> USING (SELECT PersonID, FamilyID, PersonName, ParentID FROM Person
4> WHERE FamilyID in (SELECT FamilyID from Family where FamilyName like '%DA%'))
5> AS PersonSourceTable ON (0=1)
6> WHEN NOT MATCHED THEN
7> INSERT(FamilyID, PersonName, ParentID)
8> VALUES
9> ((SELECT TOP 1 TargetID from @FamilyIdMap WHERE SourceID=FamilyID),PersonName,
10> ParentID) OUTPUT
11> INSERTED.PersonID, PersonSourceTable.PersonID
12> INTO @PersonIdMap;
It gives the output like this:
Source Table
PersonID FamilyID PersonName ParentID
1 1 ABC Null
2 1 Son of ABC 1
3 1 Son of ABC 1
4 2 XYZ NULL
5 2 Son of XYZ 4
Target Table (Copied from Source Table using above given code)
PersonID FamilyID PersonName ParentID
6 1 ABC Null
7 1 Son of ABC 1 <-- ParentID Remains as it is
8 1 Son of ABC 1 <--
9 2 XYZ NULL
10 2 Son of XYZ 4 <--
Problem in above output is it doesn't update the parentID
, I want the output to be this:
Expected Target Table
PersonID FamilyID PersonName ParentID
6 1 ABC Null
7 1 Son of ABC 6 <-- ParentID should be updated
8 1 Son of ABC 6 <--
9 2 XYZ NULL
10 2 Son of XYZ 9 <--
I know problem is at line # 10 of code
10> ParentID) OUTPUT
but what should I replace with ParentID
to update it ? Thanks in advance.