ID TXT PID
12 A 13
13 B 15
15 C Null
需要编写一个srpoc,它会将此源数据插入到其中包含标识列的目标表中
ID TXT PID
1 A 2
2 B 3
3 C Null
在目标表中,ID是标识列,PID是ID列的外键。
以下是我尝试使用tmp表的方法。但我得到的结果不是实际结果。请帮帮我。
ID TXT PID
1 A 1
2 B 2
3 C Null
drop table #tmp
Create table #tmp
(
id int identity (1,1) constraint pk_tab Primary key,
Txt varchar(10),
ParentId int NULL
CONSTRAINT FK_Categories_ParentId
FOREIGN KEY (id) REFERENCES #tmp
)
insert into #tmp(Txt)
Select Source.s from
(Select f.ID,f.T as s,g.T as p from
(select 12 as ID, 'A' as T, 13 as PID
union all
Select 13,'B',15
union all
select 15,'C',null
) f
left join
(select 12 as ID, 'A' as T, 13 as PID
union all
Select 13,'B',15
union all
select 15,'C',null
)g
on f.ID = g.PID
) Source
Select * from #tmp
update #tmp
SET
#tmp.ParentId = #tmp.ID
FROM
#tmp
INNER JOIN
(Select f.ID,f.T as s,g.T as p from
(select 12 as ID, 'A' as T, 13 as PID
union all
Select 13,'B',15
union all
select 15,'C',null
) f
left join
(select 12 as ID, 'A' as T, 13 as PID
union all
Select 13,'B',15
union all
select 15,'C',null
)g
on f.ID = g.PID
) Source
ON
#tmp.Txt = Source.p
Select * from #tmp
答案 0 :(得分:0)
我不明白如何禁止额外的列。除非这是家庭作业/工作面试/谜题,否则您只需更改代码:
Create table #tmp
(
id int identity (1,1) constraint pk_tab Primary key,
Txt varchar(10),
ParentId int NULL,
OriginalId int NULL
CONSTRAINT FK_Categories_ParentId
FOREIGN KEY (id) REFERENCES #tmp
)