System.Data.SqlClient.SqlException (0x80131904):违反唯一键约束“AK_SeqNo”。无法在对象“dbo.SeqNo”中插入重复键。
我随机收到上述 SQL Server 2005 Express 错误。从下面的存储过程中可能每 3 周一次。谁能明白为什么?
CREATE PROCEDURE [dbo].[mspResetSeqNo] @Today DATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE @DateSrc DATETIME
DECLARE @MyGUID UNIQUEIDENTIFIER
-- Check Input is Valid
IF @Today IS NULL
BEGIN
RAISERROR (N'@Today cannot be NULL', 10, 1);
RETURN 1;
END
-- Chop off the time part:
SET @DateSrc = DATEADD(d, 0, DATEDIFF(d, 0, @Today));
-- Get Current Location GUID
SET @MyGUID = dbo.MyGUID();
-- If this is the first entry for the day then initialise
INSERT INTO dbo.SeqNo(MyGUID, TheDay, LastNo)
SELECT @MyGUID, @DateSrc, 0
WHERE NOT EXISTS (
SELECT 1 FROM dbo.SeqNo AS sn
WHERE sn.MyGUID = @MyGUID AND sn.TheDay = @DateSrc
);
RETURN(0);
END
AK_SeqNo 的约束是:
ALTER TABLE [dbo].[SeqNo] ADD CONSTRAINT [AK_SeqNo] UNIQUE NONCLUSTERED
(
[TheDay] ASC,
[MyGUID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
这两种数据类型的表列是:
[MyGUID] [dbo].[DForeignKey] NOT NULL,
[TheDay] [datetime] NOT NULL,
用户定义的类型 DForeignKey 是:
CREATE TYPE [dbo].[DForeignKey] FROM [uniqueidentifier] NULL
MyGUID() 函数只是检索本地系统 ID。每个位置都有不同的 ID。
CREATE FUNCTION [dbo].[MyGUID]()
RETURNS uniqueidentifier
AS
BEGIN
DECLARE @me as uniqueidentifier
SELECT @me = MyGUID FROM Self
RETURN @me
END