【问题标题】:SQL Server procedure error - duplicate entries inserted into the tableSQL Server 过程错误 - 重复的条目插入到表中
【发布时间】:2016-09-22 05:41:02
【问题描述】:

我正在 SQL Server 中编写一个过程来插入或更新记录。

代码的更新部分工作正常,但是当我执行它进行插入时,重复的条目被插入到表中。

我创建了主键以避免此错误,但创建后我无法插入任何单条记录。

代码如下:

Alter Procedure test_case 
    @id int, 
    @name nvarchar(20)  
AS
    If exists (Select t_id from testing2 where t_id = @id) 
    begin 
        update testing2 
        set t_id = @id, t_name = @name 
        where t_id = @id 
    end 
    else
    begin
        insert into testing2 (t_id, t_name, last_date, hard)
            select 
                @id, @name, convert(date, getdate()), 'null' 
            from test
    end

在执行时显示 2 行受影响

【问题讨论】:

  • 嗯,test 表有多少行?
  • 如果update 在您的@id 与多行匹配时执行,它会更新所有这些行。没有任何数据可见性,在这里很难解决您的问题
  • 表为空。
  • @paemmi - 你为什么需要from test。你所有的值都是直接参数,可以直接在insert中使用
  • 添加.. Testing2 表是空的... 我通过通常将值插入到表中来测试更新部分。但我希望它与存储过程一起插入

标签: sql-server stored-procedures


【解决方案1】:

选择查询中不需要测试表

       insert into testing2 (t_id, t_name, last_date, hard)
        select 
            @id as t_id, @name as t_name, convert(date, getdate()) as last_date, 'null' as hard 

够了

【讨论】:

    【解决方案2】:

    我喜欢将功能分解成更小的部分,因为它可以帮助我更好地管理代码。
    也许这不是一个很好的例子,因为它很简单,但我还是会写它。

    Create Procedure Testing2_InsertData (
      @id int, 
      @name nvarchar(20)
    ) As
    Set NoCount On
    
    Insert Into testing2 
      (t_id, t_name, last_date, hard)
    Values
      ( @id, #name, GetDate(), null )
    Go
    
    
    
    Create Procedure Testing2_UpdateData (
      @id int, 
      @name nvarchar(20)
    ) As
    Set NoCount On
    
    Update testing2 Set
      t_name = @name --, maybe last_date = GetDate()
    Where ( t_id = @id )
    Go
    
    
    
    Create Procedure Testing2_SaveData (
      @id int, 
      @name nvarchar(20)
    ) As
    Set NoCount On
    
    If ( Exists( Select t_id From testing2 Where ( t_id = @id ) ) )
      Exec Testing2_UpdateData @id, @name
    Else
      Exec Testing2_InsertData @id, @name
    Go
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多