2016-09-21 43 views
0

我在SQL Server中編寫過程以插入或更新記錄。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

好吧,'test'表有多少行? – Lamak

+0

如果在您的@ id與多行匹配時執行'update',它會更新所有這些行。沒有任何數據可見性,這裏很難解決你的問題 – techspider

+0

表是空的。 – paemmi

回答

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 

足夠

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