一、建立种子表:
--DROP TABLE SST_KEYNO
IF NOT EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[SST_KEYNO]') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1)
BEGIN
CREATE TABLE [dbo].[SST_KEYNO] (
[TABLE] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[NOTE] [varchar] (12) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[DATE] [datetime] NOT NULL ,
[VALUE] [int] NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[SST_KEYNO] WITH NOCHECK ADD
CONSTRAINT [PK_SST_KEYNO] PRIMARY KEY CLUSTERED
(
[TABLE],
[NOTE],
[DATE]
) ON [PRIMARY]
END
二、存储过程实现生成规则编号:
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = 'GET_MAX_KEYNO' AND TYPE ='P')
DROP PROCEDURE GET_MAX_KEYNO
GO
CREATE PROCEDURE GET_MAX_KEYNO
(
@TABLE VARCHAR(30),
@NOTE VARCHAR(12),
@KEY_NO VARCHAR(12) OUTPUT
)
--根据传入的"表名/种子"得到最大序号
AS
BEGIN
DECLARE @MAX_KEY_NO VARCHAR(12)
DECLARE @VALUE VARCHAR(20)
DECLARE @VALUE_INT INT
DECLARE @DATE_PART VARCHAR(8) --如:090501
DECLARE @DATE_TODAY DATETIME
SET @DATE_PART = SUBSTRING(convert(varchar(10),getdate(), 112),3,8)
SET @DATE_TODAY = convert(varchar(10),getdate(),120)
SET @MAX_KEY_NO = @NOTE + @DATE_PART
DECLARE @NUM INT
SET @NUM = (SELECT COUNT(*) FROM SST_KEYNO WHERE [TABLE]=@TABLE AND NOTE=@NOTE AND [DATE]= @DATE_TODAY)
--1、在表中插入数据value = 2,返回 value = 1拼成的串
IF (@NUM = 0)
BEGIN
SET @MAX_KEY_NO = @MAX_KEY_NO + REPLACE(SPACE(11-LEN(@MAX_KEY_NO)),' ','0')+'1'
INSERT INTO SST_KEYNO ([TABLE],[NOTE],[DATE],[VALUE])
VALUES(@TABLE , @NOTE , @DATE_TODAY , 2)
END
--1、查询表中的value值,修改表中值
IF(@NUM >= 1)
BEGIN
SET @VALUE_INT = (SELECT MAX(VALUE) FROM SST_KEYNO WHERE [TABLE]=@TABLE AND NOTE=@NOTE AND [DATE]= @DATE_TODAY)
SET @VALUE = @VALUE_INT
SET @MAX_KEY_NO = @MAX_KEY_NO + REPLACE(SPACE(12-LEN(@MAX_KEY_NO)-LEN(@VALUE)),' ','0') + @VALUE
SET @VALUE_INT = @VALUE_INT + 1
UPDATE SST_KEYNO
SET VALUE = @VALUE_INT
WHERE [TABLE] = @TABLE AND NOTE = @NOTE AND [DATE]= @DATE_TODAY
END
SET @KEY_NO = @MAX_KEY_NO
END
/*
DECLARE @KEYNO VARCHAR(12)
execute
GET_MAX_KEYNO
@TABLE = '1111',
@NOTE = 'JX',
@KEY_NO = @KEYNO OUTPUT
SELECT @KEYNO
*/