您可以使用密钥表来存储第二个ID列的递增部分。该解决方案不依赖任何客户端代码,并且可以自动识别多年。当@DateAdded
参数传入先前未使用的年份时,它将ID2
基于该年份自动开始使用该列的一组新值。因此,如果将proc用于插入前几年的行,则这些行将插入带有“正确”值的增量。该GetNextID()
PROC是面向妥善处理可能出现的死锁,只有当试图更新时,会出现5个连续死锁传递一个错误给调用者tblIDs
表。
创建一个表来存储每年包含当前使用的ID值的一行,以及一个存储过程以返回要使用的新值:
CREATE TABLE [dbo].[tblIDs]
(
IDName nvarchar(255) NOT NULL,
LastID int NULL,
CONSTRAINT [PK_tblIDs] PRIMARY KEY CLUSTERED
(
[IDName] ASC
) WITH
(
PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
, FILLFACTOR = 100
)
);
GO
CREATE PROCEDURE [dbo].[GetNextID](
@IDName nvarchar(255)
)
AS
BEGIN
/*
Description: Increments and returns the LastID value from
tblIDs for a given IDName
Author: Max Vernon / Mike Defehr
Date: 2012-07-19
*/
SET NOCOUNT ON;
DECLARE @Retry int;
DECLARE @EN int, @ES int, @ET int;
SET @Retry = 5;
DECLARE @NewID int;
WHILE @Retry > 0
BEGIN
SET @NewID = NULL;
BEGIN TRY
UPDATE dbo.tblIDs
SET @NewID = LastID = LastID + 1
WHERE IDName = @IDName;
IF @NewID IS NULL
BEGIN
SET @NewID = 1;
INSERT INTO tblIDs (IDName, LastID)
VALUES (@IDName, @NewID);
END
SET @Retry = -2; /* no need to retry since the
operation completed */
END TRY
BEGIN CATCH
IF (ERROR_NUMBER() = 1205) /* DEADLOCK */
SET @Retry = @Retry - 1;
ELSE
BEGIN
SET @Retry = -1;
SET @EN = ERROR_NUMBER();
SET @ES = ERROR_SEVERITY();
SET @ET = ERROR_STATE()
RAISERROR (@EN,@ES,@ET);
END
END CATCH
END
IF @Retry = 0 /* must have deadlock'd 5 times. */
BEGIN
SET @EN = 1205;
SET @ES = 13;
SET @ET = 1
RAISERROR (@EN,@ES,@ET);
END
ELSE
SELECT @NewID AS NewID;
END
GO
您的表以及在其中插入行的proc:
CREATE TABLE dbo.Cond
(
CondID INT NOT NULL
CONSTRAINT PK_Cond
PRIMARY KEY CLUSTERED
IDENTITY(1,1)
, CondID2 VARCHAR(30) NOT NULL
, Date_Added DATE NOT NULL
);
GO
CREATE PROCEDURE dbo.InsertCond
(
@DateAdded DATE
)
AS
BEGIN
DECLARE @NextID INT;
DECLARE @Year INT;
DECLARE @IDName NVARCHAR(255);
SET @Year = DATEPART(YEAR, @DateAdded);
DECLARE @Res TABLE
(
NextID INT NOT NULL
);
SET @IDName = 'Cond_' + CONVERT(VARCHAR(30), @Year, 0);
INSERT INTO @Res (NextID)
EXEC dbo.GetNextID @IDName;
INSERT INTO dbo.Cond (CondID2, Date_Added)
SELECT CONVERT(VARCHAR(30), NextID) + '/' +
SUBSTRING(CONVERT(VARCHAR(30), @Year), 3, 2), @DateAdded
FROM @Res;
END
GO
插入一些样本数据:
EXEC dbo.InsertCond @DateAdded = '2015-12-30';
EXEC dbo.InsertCond @DateAdded = '2015-12-31';
EXEC dbo.InsertCond @DateAdded = '2016-01-01';
EXEC dbo.InsertCond @DateAdded = '2016-01-02';
显示两个表:
SELECT *
FROM dbo.Cond;
SELECT *
FROM dbo.tblIDs;
结果:
密钥表和存储过程来自这个问题。