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

请大家帮个忙
表t1
busdate           pno             medicalcode
2007.05.08       1               0101
2007.05.08       1
2007.05.08       2               0202
2007.05.08       2               0303
2007.05.08       2        
2007.05.09       1               0404
2007.05.09       2               0101
当medicalcode   为空时  
那么这个medicalcode值要更新为同一天   同一个pno号的   medicalcode值,但medicalcode值有可能很多个的,只要选第一个   medicalcode   就行了
如何实现????


------解决方案--------------------
declare @t table(busdate char(10),pno int,medicalcode char(4))
insert @t
select '2007.05.08 ',1, '0101 ' union all
select '2007.05.08 ',1, ' ' union all
select '2007.05.08 ',2, '0202 ' union all
select '2007.05.08 ',2, '0303 ' union all
select '2007.05.08 ',2, ' ' union all
select '2007.05.09 ',1, '0404 ' union all
select '2007.05.09 ',2, '0101 '


select * from @t
update @t
set medicalcode = (
select distinct top 1 a.medicalcode from @t a
where a.pno = c.pno and a.busdate = c.busdate and a.medicalcode <> ' ')
from @t c
where c.medicalcode = ' '

select * from @t

/*

所影响的行数为 7 行)

busdate pno medicalcode
---------- ----------- -----------
2007.05.08 1 0101
2007.05.08 1
2007.05.08 2 0202
2007.05.08 2 0303
2007.05.08 2
2007.05.09 1 0404
2007.05.09 2 0101

(所影响的行数为 7 行)


(所影响的行数为 2 行)

busdate pno medicalcode
---------- ----------- -----------
2007.05.08 1 0101
2007.05.08 1 0101
2007.05.08 2 0202
2007.05.08 2 0303
2007.05.08 2 0202
2007.05.09 1 0404
2007.05.09 2 0101

(所影响的行数为 7 行)


*/
------解决方案--------------------
create proc up_test(@busdate varchar(20))
as
update t1
set medicalcode=(select top 1 medicalcode from t1 a where t1.busdate=a.busdate and t1.pno=a.pno)
from t1
where isnull(medicalcode, ' ')= ' '
and busdate=@busdate
------解决方案--------------------

declare @busdate nvarchar(20)
set @busdate= '2007.05.08 '
update t1 set medicalcode=(select top 1 a.medicalcode )
from t1 inner join t1 a on t1.busdate=a.busdate and t1.pno=a.pno
where t1.medicalcode= ' ' and a.medicalcode <> ' ' and t1.busdate=@busdate