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

求一存储过程,得到字段的最大值,并自动加1后插入--较难
求一存储过程,得到字段的最大值,并自动加1后插入--较难

表T_DJ_NSRJBXX结构如下

ID SWGLM
1 2321321200001
2 2321321200002
3 2321321300001
4 2321321300002
5 2321321300003
6 2321321300004
...

SWGLM类型为varchar(13),

假设操作员变量为:czy

SWGLM字段前八位为czy(操作员号)。比如:23213213,23213212,   23213211等等

这时如果23213212操作员对表T_DJ_NSRJBXX插入数据时,首先查找SWGLM字段的前八位,和自已的操作员号相符时,得到后五位的最大值,比如上表中23213212操作员的最大值为“2”,那么他将插入字段SWGLM的数据即为“2321321200003”,如果是23213213操作员,那么他将插入的数据即为“2321321300005”

注意:如果是23213211操作员,因为其在表中尚无记录,则其将插入的数据为“2321321100001”


假设存储过程将带入的变量为@czy(操作员号),请问如何来写这一段存储过程?

谢谢

------解决方案--------------------
create proc pr_test
@czy varchar(20),
@SWGLM varchar(20) output
as
declare @i int
select @i=cast(stuff(max(SWGLM),1,8, ' ') as int) from T_DJ_NSRJBXX
where SWGLM like @czy+ '% '
set @i=@i+1
set @SWGLM=@czy+ '00000 '+right(cast(@i as varchar),5)

go
------解决方案--------------------
create table ttt(id varchar(10),SWGLM varchar(13))

insert into ttt values( '1 ', '2321321200001 ')
insert into ttt values( '2 ', '2321321200002 ')
insert into ttt values( '3 ', '2321321300001 ')
insert into ttt values( '4 ', '2321321300002 ')
insert into ttt values( '5 ', '2321321400003 ')
insert into ttt values( '6 ', '2321321500004 ')

ALTER proc sp_insert(@SWGL VARCHAR(8),@id varchar(2))
AS
DECLARE @max_SW VARCHAR(8000)
SELECT @max_SW=SWGLM FROM ttt where left(SWGLM,8)=@SWGL
SET @max_SW=right(@max_SW,5)
INSERT INTO ttt values(@id,@SWGL+RIGHT(1000000+CAST(@max_SW AS INT)+1,5) )


exec sp_insert '23213214 ', '7 '

------解决方案--------------------
id SWGLM
---------- -------------
1 2321321200001
2 2321321200002
3 2321321300001
4 2321321300002
5 2321321400003
6 2321321500004
7 2321321400004

------解决方案--------------------
create table ttt(id varchar(10),SWGLM varchar(13))

insert into ttt values( '1 ', '2321321200001 ')
insert into ttt values( '2 ', '2321321200002 ')
insert into ttt values( '3 ', '2321321300001 ')
insert into ttt values( '4 ', '2321321300002 ')
insert into ttt values( '5 ', '2321321400003 ')
insert into ttt values( '6 ', '2321321500004 ')

create proc sp_insert(@SWGL VARCHAR(8),@id varchar(2))
AS
DECLARE @max_SW VARCHAR(8000)
SELECT @max_SW=SWGLM FROM ttt where left(SWGLM,8)=@SWGL
SET @max_SW=right(@max_SW,5)
INSERT INTO ttt values(@id,@SWGL+RIGHT(1000000+CAST(@max_SW AS INT)+1,5) )


exec sp_insert '23213214 ', '7 '
=============
id SWGLM
---------- -------------
1 2321321200001
2 2321321200002
3 2321321300001
4 2321321300002
5 2321321400003
6 2321321500004
7 2321321400004

------解决方案--------------------
--創建測試環境
create table T_DJ_NSRJBXX(
ID int identity(1, 1),
SWGLM char(13))

insert into T_DJ_NSRJBXX
select '2321321200001 '