日期:2014-05-18  浏览次数:20358 次

高手帮忙!这样的存储过程怎么写

 ID NAME TYPE LENGTH CitedID
 01 S1 INT 1 NULL
 02 NULL NULL 5 01 
 03 NULL NuLL 8 02
现在有这样一张表 我要抓03 但是03里面的字段没有内容 (要是03里面有了就直接显示,),就要通过引用关系( CitedID)到被引用里面的ID去找要是被引用里面的字段也为空在到被引用去找,要是有了就插入到03的字段里面去 并显示出来)(要是03里字段数据的就不被插入 如length 是8 就不用插入上一个的 直接抓出)
)

------解决方案--------------------
SQL code
--原始数据:@T
declare @T table(ID varchar(2),NAME varchar(4),TYPE varchar(4),LENGTH int,CitedID varchar(4))
insert @T
select '01','S1','INT',1,null union all
select '02',null,null,5,'01' union all
select '03',null,null,8,'02'

while exists (select 1 from @T where NAME is null or TYPE is null or LENGTH is null)
    update a set a.NAME=isnull(a.name,b.name),a.TYPE=isnull(a.TYPE,b.TYPE),a.LENGTH=isnull(a.LENGTH,b.LENGTH)
        from @T a join @T b on a.CitedID=b.ID
        where a.NAME is null or a.TYPE is null or a.LENGTH is null

select * from @T

/*
ID   NAME TYPE LENGTH      CitedID 
---- ---- ---- ----------- ------- 
01   S1   INT  1           NULL
02   S1   INT  5           01
03   S1   INT  8           02
*/

------解决方案--------------------
SQL code

declare @T table(ID varchar(2),NAME varchar(4),TYPE varchar(4),LENGTH int,CitedID varchar(4))
insert @T
select '01','S1','INT',1,null union all
select '02',null,null,5,'01' union all
select '03',null,null,8,'02'

select * from @T

declare @id int
SET @ID=03
IF exists(SELECT ID FROM @T WHERE ID=@id AND NAME is NOT null AND TYPE is NOT null AND LENGTH is NOT null)
   begin
    SELECT * FROM @T WHERE ID=@id
   end
else
  begin
   while exists(select 1 from @T where ID=@id AND (NAME is null or TYPE is null or LENGTH is null))
      update a set a.NAME=isnull(a.name,b.name),a.TYPE=isnull(a.TYPE,b.TYPE),a.LENGTH=isnull(a.LENGTH,b.LENGTH)
        from @T a join @T b on a.CitedID=b.ID
        where a.NAME is null or a.TYPE is null or a.LENGTH is null
   select * from @T where ID=@id
  end
/*
ID   NAME TYPE LENGTH      CitedID
---- ---- ---- ----------- -------
03   S1   INT  8           02
*/