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 --存储
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 --输出结果