update rk_bak set rkdh='RK'+CONVERT(char(4),rkrq,12)
+right(10000+(
select count(*) from rk_bak
where datediff(month,rkrq,a.rkrq)=0 and rkrq<a.rkrq
or(rkrq=a.rkrq and id<=a.id)
),4)
from rk_bak a
--测试数据
create table rk_bak(rkrq datetime,rkdh char(10))
insert rk_bak(rkrq)
select '1933/04/22'
union all select '1933/04/22'
union all select '2000/01/01'
union all select '2001/04/03'
union all select '2001/04/03'
union all select '2001/04/03'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/04'
union all select '2001/04/05'
union all select '2001/04/05'
union all select '2001/04/05'
union all select '2001/04/05'
union all select '2001/04/06'
go
--更新处理
declare @rq datetime,@i int
update rk_bak set @i=case datediff(month,rkrq,@rq) when 0 then @i+1 else 10001 end
,rkdh='RK'+CONVERT(char(4),rkrq,12)+right(@i,4)
,@rq=rkrq
go
--使用SQLSERVER自带的例子数据库northwind
use northwind
go
select xuhao='PK'+convert(char(4),orderdate,12)+
right('0000'+cast((select count(*) from orders a where a.orderID<=b.orderID and datediff(month,a.orderDate,b.orderDate)=0)as varchar(4)),4),
orderID,orderDate from orders b