根据父级名称找出所有子集的SQL语句

来源:互联网 发布:c语言字符数组默认 编辑:程序博客网 时间:2024/05/29 05:07
if exists (select 1
            
from  sysobjects
           
where  id = object_id('newtable1')
            
and   type = 'U')
begin 
drop table newtable1--用来存放所有子集ID的临时表
end

if exists (select 1
            
from  sysobjects
           
where  id = object_id('seaskytable')
            
and   type = 'U')
begin 
drop table seaskytable--中间过度的临时表
end
select B_P_ID into seaskytable from B_Province where B_P_Name like '%上海%'
select B_P_ID into newtable1 from seaskytable where B_P_ID is null
while exists(select * from B_Province where B_P_ParentID in (select * from seaskytable where B_P_ID not in (select * from newtable1)))
begin
SET  IDENTITY_INSERT seaskytable off
SET  IDENTITY_INSERT newtable1 on
insert into  newtable1(B_P_ID)  select B_P_ID from seaskytable where B_P_ID not in (select * from newtable1)

SET  IDENTITY_INSERT newtable1 off
SET  IDENTITY_INSERT seaskytable ON
insert into seaskytable(B_P_ID) select B_P_ID from B_Province where B_P_ParentID in (select * from seaskytable)
end
SET  IDENTITY_INSERT seaskytable off
SET  IDENTITY_INSERT newtable1 on
insert into  newtable1(B_P_ID)  select B_P_ID from seaskytable where B_P_ID not in (select * from newtable1)

select * from B_Province where B_P_ID in (select * from  newtable1)
原创粉丝点击