存在的SQL不会过滤?

时间:2013-02-07 04:50:53

标签: sql sql-server tsql sql-server-2005-express

  

System.Data.SqlClient.SqlException(0x80131904):违反UNIQUE   KEY约束'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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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)
      );

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