2

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
4

2 回答 2

1

问题是并发问题。单实例检查移至调用此存储过程的代码点之后。谢谢你的帮助。至少我学到了 2 更多关于 t-sql 函数的知识。

于 2013-02-15T06:02:06.827 回答
0

这是将记录添加到表中的唯一方法吗?

我也将CONVERT用于我的比较,如下所示:

  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
      CONVERT(VARCHAR(11), sn.TheDay, 101) = CONVERT(VARCHAR(11), @Today, 101)
      );

这使您不必将中间值存储在变量中。

于 2013-02-13T23:26:46.187 回答