select top 1 from tb1 where 条件(这里如何写?)
if ....找到,则返回值。。。(这里如何写?)
UPDATE TB1 ......
else
INSERT ......
...全文
839打赏收藏
存储过程里如何得到SELECT句返回值
若我在表tb1找到满足条件时,我用UPDATE修改这行记录,否则用INSERT新增一行新记录。 究竟用TOP 1, 还是用count() ,或其它? select top 1 from tb1 where 条件(这里如何写?) if ....找到,则返回值。。。(这里如何写?) UPDATE TB1 ...... else INSERT ......
找到就修改,否则就插入,直接用两句语句:
假设是从另一个表中查到的数据集:
先更新:
update a set col=b.col from tb1 a --这是被修改表
inner join tb2 b --这是提供数据的表
on a.id=b.id
再插入
insert into tb1
select * from tb2 where not exists(select 1 from tb1 where id=tb2.id)
[Quote=引用 3 楼 dawugui 的回复:]
if exists(select 1 from tb1 where 条件) -- 不存在
insert into ...
else --存在
update ...
[/Quote]搞反了.应该是:
if not exists(select 1 from tb1 where 条件) -- 不存在
insert into ...
else --存在
update ...