如何使用存储过程避免重复记录

时间:2018-05-03 04:04:54

标签: sql-server stored-procedures

我想编写一个存储过程来将数据插入表中,还要检查是否已存在相同的数据?

如果是,那么异常抛出已经存在。但我不知道我应该在哪里添加例外。请帮忙。

ALTER PROCEDURE [dbo].[datakutipantest1]
AS
BEGIN
    DECLARE @ModifiedDate datetime = GETDATE()

    INSERT INTO spk_DataKutipan ([NO_BIL], [NO_AKAUN], [TKH_BAYAR],
  [STESYEN], [AMAUN_BAYAR], [JENIS_BAYAR], [NO_RESIT], [STATUS], [NO_VOT], [TKH_MODIFIKASI])
        SELECT
            D.BillNo,
            D.AccountNo,
            D.TxDate,
            D.ReferenceCode,
            D.Amount,
            PaymentTypeId,
            D.ReferenceNo,
            D.Status,
            D.RevenueCode,
            @ModifiedDate
        FROM 
            (SELECT
                 B.ComponentId,
                 B.AccountNo,
                 B.BillNo,
                 B.RevenueCode,
                 B.Amount,
                 B.TxId,
                 ReferenceNo,
                 B.ReferenceCode,
                 status,
                 TxDate
             FROM 
                 (SELECT
                      A.ComponentId,
                      A.TxId,
                      AccountNo,
                      BillNo,
                      RevenueCode,
                      Amount,
                      C.ReferenceCode
                  FROM 
                      rcs_TxBillItem A
                  INNER JOIN 
                      (SELECT
                           ComponentId,
                           ComponentName,
                           ReferenceCode
                       FROM 
                           rcs_Component
                       WHERE  
                           IsDeleted = 0) C ON C.ComponentId = A.ComponentId) B
                  INNER JOIN  
                      rcs_TxBill P ON P.TxId = B.TxId) D

             INNER JOIN 
                 rcs_TxBillPayment E ON E.TxId = D.TxId
END
GO

2 个答案:

答案 0 :(得分:0)

CREATE PROCEDURE [dbo].[Useradd]
      @username varchar(20),
      @pword nvarchar(20),
      @empname varchar(20),
      @email nvarchar(50),
      @designation varchar(20),
      @reportto varchar(20) AS
  IF (SELECT COUNT(*) FROM Users WHERE username= @username) < 1
    BEGIN   
      INSERT INTO Users(username,pword,empname,email,designation,reportto)    
      VALUES(@username,@pword,@empname,@email,@designation,@reportto)
    END

答案 1 :(得分:0)

考虑使用MERGE

MERGE <target_table> [AS TARGET]
USING <table_source> [AS SOURCE]
ON <search_condition> --For example ColumnSource = ColumnTable
WHEN MATCHED --Rows already exist
   THEN UPDATE target_table SET ... --Do Update for example
WHEN NOT MATCHED BY TARGET --Rows not exist on Target Table
   THEN INSERT(...) VALUES(...) --Do Insert for example
WHEN NOT MATCHED BY SOURCE --Rows not exist on Source table but exists on Target Table
   THEN DELETE ... --Do Delete for example

MERGE语句基本上根据您指定的条件将来自源结果集的数据合并到目标表,以及来自源的数据是否已存在于目标中。新的SQL命令在单个原子语句中组合条件INSERT,UPDATE和DELETE命令的顺序,具体取决于记录的存在。