需求:需要生成下面的序列號(hào),前半部分是yyyymmdd格式的年月日時(shí)間數(shù)字,后半部分則是每天都從1順序增長(zhǎng)的數(shù)字,位數(shù)要固定,中間不足的補(bǔ)0。
在SQL Server 2000數(shù)據(jù)庫(kù)中測(cè)試后通過(guò)如下代碼,功能實(shí)現(xiàn)如下:
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
--存儲(chǔ)過(guò)程開(kāi)始
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)
--保存取得的當(dāng)前時(shí)間
SET @DATE = GETDATE()
SET @YYYY = DATEPART(yyyy, @DATE)
SET @MM = DATEPART(mm, @DATE)
SET @DD = DATEPART(dd, @DATE)
--位數(shù)不夠的前面補(bǔ)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
--取出表中當(dāng)前日期的已有的最大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
--如果未取出來(lái)
IF @NEW_ID IS NULL
--說(shuō)明還沒(méi)有當(dāng)前日期的編號(hào),則直接從1開(kāi)始編號(hào)
SET @NEW_ID = (@YYYY+@MM+@DD+'00000001')
--如果取出來(lái)了
ELSE
BEGIN
DECLARE @NUM VARCHAR(8)
--取出最大的編號(hào)加上1
SET @NUM = CONVERT(VARCHAR, (CONVERT(INT, RIGHT(@NEW_ID, 8)) + 1))
--因?yàn)榻?jīng)過(guò)類型轉(zhuǎn)換,丟失了高位的0,需要補(bǔ)上
SET @NUM = REPLICATE('0', 8 - LEN(@NUM)) + @NUM
--最后返回日期加編號(hào)
SET @NEW_ID = @YYYY+@MM+@DD + @NUM
END
END
GO
--執(zhí)行20次調(diào)用及插入數(shù)據(jù)測(cè)試
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
--輸出結(jié)果
/**//*
my_id
----------------
2006092700000001
2006092700000002
2006092700000003
2006092700000004
2006092700000005
2006092700000006
2006092700000007
2006092700000008
2006092700000009
2006092700000010
2006092700000011
2006092700000012
2006092700000013
2006092700000014
2006092700000015
2006092700000016
2006092700000017
2006092700000018
2006092700000019
2006092700000020
*/
注釋:原來(lái)yyyymmdd格式的日期直接這樣取即可:
SELECT CONVERT(CHAR(8), GETDATE(), 112)
--輸出結(jié)果:
/**//*
--------
20060927
*/
更多信息請(qǐng)查看IT技術(shù)專欄