Home > Database > Mysql Tutorial > SQL Server自动生成日期加数字的序列号

SQL Server自动生成日期加数字的序列号

WBOY
Release: 2016-06-07 17:58:49
Original
1283 people have browsed it

需要生成下面的序列号,前半部分是yyyymmdd格式的年月日时间数字,后半部分则是每天都从1顺序增长的数字,位数要固定,中间不足的补0。

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 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
--输出结果
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template