日期:2014-05-17 浏览次数:20611 次
declare @A表 table
(id int identity(1,1),title varchar(5),memo varchar(5),code varchar(5))
insert into @A表
select '标题1','内容1','TT001' union all
select '标题2','内容2','ST001' union all
select '标题3','内容3','TT002' union all
select '标题4','内容4','ST008'
declare @B表 table
(id int identity(1,1),title varchar(5),memo varchar(5),code varchar(2))
insert into @B表
select '标题1','内容1','ST' union all
select '标题2','内容2','ST' union all
select '标题3','内容3','TT'
--插入数据 【这个位置实际上是可以不用外层嵌套的,嵌套是为了你看起来直观】
insert into @A表
select
title,memo,
code+right('000'+ltrim((select count(*) from @B表
where code=t.code and id<=t.id)
+(select max(right(code,3)+0) from @A表
where left(code,2)=t.code)),3)
from @B表 t
--查看数据
select * from @A表
/*
id title memo code
----------- ----- ----- -----
1 标题1 内容1 TT001
2 标题2 内容2 ST001
3 标题3 内容3 TT002
4 标题4 内容4 ST008
5 标题1 内容1 ST009
6 标题2 内容2 ST010
7 标题3 内容3 TT003
*/