SQL Where Exists Doesn't Filter?

对着背影说爱祢 提交于 2019-12-22 13:59:52

问题


System.Data.SqlClient.SqlException (0x80131904): Violation of UNIQUE KEY constraint 'AK_SeqNo'. Cannot insert duplicate key in object 'dbo.SeqNo'.

I get the above SQL Server 2005 Express error randomly. Maybe once every 3 weeks from the stored procedure below. Can anyone see why?

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

The constraint for AK_SeqNo is:

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]

The table column for those 2 data types are:

[MyGUID] [dbo].[DForeignKey] NOT NULL,
[TheDay] [datetime] NOT NULL,

The user defined type DForeignKey is:

CREATE TYPE [dbo].[DForeignKey] FROM [uniqueidentifier] NULL

The MyGUID() function is simply retrieving the local system ID. Every location has a different ID.

CREATE FUNCTION [dbo].[MyGUID]()
RETURNS uniqueidentifier
AS
BEGIN
DECLARE @me as uniqueidentifier
SELECT @me = MyGUID FROM Self
RETURN @me
END

回答1:


The problem was a concurrency issue. The single instance check was moved to after the point in code where this stored procedure was called. Thanks for your help. At least I learned a thing of 2 more about t-sql functions.




回答2:


Is this the only way in which records get added to the table?

I'd also use CONVERT for my comparison, something like this:

  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)
      );

This gets you away from having to store the intermediate value in a variable.



来源:https://stackoverflow.com/questions/14743785/sql-where-exists-doesnt-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!