SQL Server过程错误 - 插入表中的重复条目

时间:2016-09-21 20:23:13

标签: sql-server stored-procedures

我正在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行受影响

2 个答案:

答案 0 :(得分:0)

您不需要选择查询中的测试表

       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 

就够了

答案 1 :(得分:0)

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

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