存储过程里如何得到SELECT句返回值

sunfor 2011-11-01 04:54:09
若我在表tb1找到满足条件时,我用UPDATE修改这行记录,否则用INSERT新增一行新记录。

究竟用TOP 1, 还是用count() ,或其它?

select top 1 from tb1 where 条件(这里如何写?)
if ....找到,则返回值。。。(这里如何写?)
UPDATE TB1 ......
else
INSERT ......
...全文
83 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
-晴天 2011-11-01
  • 打赏
  • 举报
回复
找到就修改,否则就插入,直接用两句语句:
假设是从另一个表中查到的数据集:
先更新:
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)
sunfor 2011-11-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dawugui 的回复:]
if exists(select 1 from tb1 where 条件) -- 不存在
insert into ...
else --存在
update ...
[/Quote]
呵。。。忘记用exists,THANKS!
dawugui 2011-11-01
  • 打赏
  • 举报
回复
[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 ...
jwdream2008 2011-11-01
  • 打赏
  • 举报
回复
if exists(select 1 from TB where ...)
begin
update.....
end
else
begin
insert ....
end
快溜 2011-11-01
  • 打赏
  • 举报
回复

--或者
if exists(select top 1 from tb1 where 条件(这里如何写?))
UPDATE TB1 ......
else
INSERT ......
--小F-- 2011-11-01
  • 打赏
  • 举报
回复
if exists(select 1 from ....where ....)
update..
else
insert...
dawugui 2011-11-01
  • 打赏
  • 举报
回复
if exists(select 1 from tb1 where 条件) -- 不存在
insert into ...
else --存在
update ...
快溜 2011-11-01
  • 打赏
  • 举报
回复
sql08可以使用merge
-晴天 2011-11-01
  • 打赏
  • 举报
回复
找到就修改,用不着top:
update tb1 set col=newvalue where 条件

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧