22,233
社区成员
发帖
与我相关
我的任务
分享
create table tb(col varchar(12))
insert into tb values('S20090323001')
insert into tb values('S20090323002')
go
DECLARE @currentMaxV VARCHAR(12),@theValue VARCHAR(12)
SELECT @currentMaxV=MAX(col) FROM tb WHERE col LIKE 'S' + CONVERT(VARCHAR(10),GETDATE(),112) + '[0-9][0-9][0-9]'
SELECT @theValue = CASE WHEN @currentMaxV IS NULL THEN 'S' + CONVERT(VARCHAR(10),GETDATE(),112) + '001' ELSE LEFT(@currentMaxV,9) + RIGHT(1000 + RIGHT(@currentMaxV,3) * 1+1,3) END
SELECT @theValue
/*
S20090324001
*/
GO
DROP TABLE tb
GO
--只需要插入这3个值就可以了,在插入以后,学号自动生成。
insert student(姓名,性别,籍贯) values()
create trigger trig_insert_students on student
for insert
as
update a set 学号='s'+convert(varchar(8),getdate(),112)+right('000'+rtrim(isnull((select max(right(学号,3)) from student where left(学号,9)='s'+convert(varchar(8),getdate(),112)),'000')+1),3)
from student a, inserted b
where a.姓名=b.姓名 and a.性别=b.性别 and a.籍贯=b.籍贯
create table tb(col varchar(12))
insert into tb values('S20090323001')
insert into tb values('S20090323002')
go
declare @rtn as varchar(12)
if exists(select 1 from tb where substring(col,2,8) = convert(varchar(8),getdate(),112))
set @rtn = (select 's' + convert(varchar(8),getdate(),112) + right('000'+cast(cast(right(max(col),3) as int) + 1 as varchar),3) from tb where substring(col,2,8) = convert(varchar(8),getdate(),112))
else
set @rtn = 's' + convert(varchar(8),getdate(),112) + '001'
print @rtn
drop table tb
/*
s20090323003
*/
--将系统时间更改为2009-03-24,再次运行.
create table tb(col varchar(12))
insert into tb values('S20090323001')
insert into tb values('S20090323002')
go
declare @rtn as varchar(12)
if exists(select 1 from tb where substring(col,2,8) = convert(varchar(8),getdate(),112))
set @rtn = (select 's' + convert(varchar(8),getdate(),112) + right('000'+cast(cast(right(max(col),3) as int) + 1 as varchar),3) from tb where substring(col,2,8) = convert(varchar(8),getdate(),112))
else
set @rtn = 's' + convert(varchar(8),getdate(),112) + '001'
print @rtn
drop table tb
/*
s20090324001
*/
declare @rtn as varchar(12)
if exists(select 1 from tb where substring(col,2,8) = convert(varchar(8),getdate(),112))
set @rtn = select 's' + convert(varchar(8),getdate(),112) + right('000'+cast(cast(right(max(col),3) as int) + 1 as varchar),3) from tb where substring(col,2,8) = convert(varchar(8),getdate(),112)
else
set @rtn = 's' + convert(varchar(8),getdate(),112) + '001'
print @rtn