zoukankan      html  css  js  c++  java
  • 多线程重复插入数据检测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种高并发情况更好。

     

  • 相关阅读:
    Prometheus监控学习笔记之Prometheus监控简介
    GO语言学习笔记之Linux环境下安装GO语言
    Jetson tx1 安装ROS
    ssh Jetson tk1
    Jetson tk1 安装 Intel 7260 无线网卡驱动
    ubuntu 14.04 软件中心闪退解决方案
    Jetson tk1 刷机后要做的几件事
    Jetson tk1 安装 usbtoserials 驱动(重新刷机)
    usbserials
    ubuntu 14.04 安装 eclipse
  • 原文地址:https://www.cnblogs.com/yanzhenan/p/2263708.html
Copyright © 2011-2022 走看看