多线程重复插入数据检测SQL



 

--

今天帮同事解决一个问题,就是线程插入检测数据重复的问题

create table TblDup(a int)

select * from TblDup

 

 

方案1

 

create unique index idx_TblDup_a on TblDup(a)

 

 

declare @a int

set @a=1

INSERT INTO TblDup (a) 

SELECT @a

WHERE NOT EXISTS (SELECT a

              FROM TblDup 

              WHERE a=@a) 

 

方案2

BEGIN TRY

   INSERT into TblDup(a) values(1)

END TRY

BEGIN CATCH

DECLARE

        @ErrorMessage    NVARCHAR(4000),

        @ErrorNumber     INT,

        @ErrorSeverity   INT,

        @ErrorState      INT,

        @ErrorLine       INT,

        @ErrorProcedure  NVARCHAR(200);

 

    -- Assign variables to error-handling functions that

    -- capture information for RAISERROR.

    SELECT

        @ErrorNumber = ERROR_NUMBER(),

        @ErrorSeverity = ERROR_SEVERITY(),

        @ErrorState = ERROR_STATE(),

        @ErrorLine = ERROR_LINE(),

        @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

 

    -- Build the message string that will contain original

    -- error information.

    SELECT @ErrorMessage =

        N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' +

            'Message: '+ ERROR_MESSAGE();

 

    -- Raise an error: msg_str parameter of RAISERROR will contain

    -- the original error information.

   

 

    IF @ErrorNumber <> 2601

      RAISERROR

        (

        @ErrorMessage,

        @ErrorSeverity,

        1,              

        @ErrorNumber,    -- parameter: original error number.

        @ErrorSeverity,  -- parameter: original error severity.

        @ErrorState,     -- parameter: original error state.

        @ErrorProcedure, -- parameter: original error procedure name.

        @ErrorLine       -- parameter: original error line number.

        );

END CATCH

 

 

两种方法第2种高并发情况更好。

 

posted @ 2011-11-25 18:51  羽化成蝶  阅读(701)  评论(0编辑  收藏  举报