.
在sql server 2000数据库中测试后通过如下代码,功能实现如下:
use master
go
if exists(select * from dbo.sysdatabases where name='my_test_database')
drop database [my_test_database]
go
create database [my_test_database]
go
use [my_test_database]
go
create table [my_table] ([my_id] varchar(16))
go
--存储过程开始
create procedure get_new_id
@new_id varchar(16) output
as
begin
declare @date datetime
declare @yyyy varchar(4)
declare @mm varchar(2)
declare @dd varchar(2)
--保存取的地当前时间
set @date = getdate()
set @yyyy = datepart(yyyy, @date)
set @mm = datepart(mm, @date)
set @dd = datepart(dd, @date)
--位数不够地前面补0
set @yyyy = replicate('0', 4 - len(@yyyy)) + @yyyy
set @mm = replicate('0', 2 - len(@mm)) + @mm
set @dd = replicate('0', 2 - len(@dd)) + @dd
--取出表中当前日期地已有地最大id
set @new_id = null
select top 1 @new_id = [my_id] from [my_table] where [my_id] like @yyyy+@mm+@dd+'%' order by [my_id] desc
--如果未取出来
if @new_id is null
--说明还没有当前日期地编号,则直接从1开始编号
set @new_id = (@yyyy+@mm+@dd+'00000001')
--如果取出来了
else
begin
declare @num varchar(8)
--取出最大地编号加上1
set @num = convert(varchar, (convert(int, right(@new_id, 8)) + 1))
--因为经过类型转换,丢失了高位地0,需要补上
set @num = replicate('0', 8 - len(@num)) + @num
--最后返回日期加编号
set @new_id = @yyyy+@mm+@dd + @num
end
end
go
--执行20次调用及插入数据测试
declare @n int
set @n = 0
while @n < 20
begin
declare @new_id varchar(16)
execute get_new_id @new_id output
insert into [my_table] ([my_id]) values (@new_id)
set @n = @n + 1
end
select * from [my_table]
go
--输出结果
/**//*
my_id
----------------
2006092700000001
2006092700000002
2006092700000003
2006092700000004
2006092700000005
2006092700000006
2006092700000007
2006092700000008
2006092700000009
2006092700000010
2006092700000011
2006092700000012
2006092700000013
2006092700000014
2006092700000015
2006092700000016
2006092700000017
2006092700000018
2006092700000019
2006092700000020
*/
注释:原来yyyymmdd格式地日期直接这样取即可:
select convert(char(8), getdate(), 112)
--输出结果:
/**//*
--------
20060927
*/
:
中国足彩网信息请查看IT技术专栏