【发布时间】: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