表:
create table users
(
id nvarchar(50),
name nvarchar(50)
)
存储过程:
alter PROCEDURE ListIdBuild
(
@action INT = 1, -- 类型 如1是生成一种编号,2是生成另一种编号
@lstId NVARCHAR(50) = NULL OUTPUT
)
AS
DECLARE
@prefix NVARCHAR(9),
@maxId INT,
@lstPre NVARCHAR(2)
BEGIN
SET @prefix = CONVERT(nchar(6), GETDATE(), 12)
IF @action = 1 --类型
BEGIN
SELECT @lstId = MAX([Id]) FROM users WHERE SUBSTRING([Id], 2, 2) = LEFT(@prefix, 2)
SET @lstPre = 'U'
END
IF @lstId IS NULL SET @lstId = '00000'
SET @lstId = RIGHT(@lstId, 5)
SET @maxId = CAST (@lstId AS int) + 1
SET @lstId = CONVERT(NVARCHAR(12), @maxId)
SET @lstId = RIGHT('000000' + @lstId, 5)
SET @lstId = @lstPre+ @prefix + @lstId
END
调用:
declare @id nvarchar(50)
exec ListIdBuild 1,@id out
print @id
得到 以字母 "U" 为前缀后面跟日期的ID号 如:U07101100001