很简单的问题,可是我不会,那位大侠能帮帮我呢?关于存储过程的!!!

林巅峰 2004-04-07 10:23:45
事情是这个样子的,我要写一个存储过程!

我数据库中有两个表 table1 主键是iid 和table2 主键 是iid
这两个表的结构是一样的,但是里面的数据不同。现在我想要完成这样的工作,先去table1里去查找iid=0的数据 如果table1里面没有我就去table2里面去查,如果table2里面有我就要返回这条记录并且 把这条记录insert到table1里面去再把它从table2里面delete掉。

这样的存储过程怎么实现呢,我试了很久也不可以,我是新学sqlserver的,我希望大家能帮我。

谢谢关注的人们。
...全文
85 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2004-04-07
  • 打赏
  • 举报
回复
--处理的存储过程
create proc p_process
as
if not exists(select 1 from table1 where iid=0) --检查在table1中是否存在
begin
set xact_abort on
begin tran --用事务处理,保证数据处理成功
insert table1 select * from table2 where iid=0 --插入到table1`
if @@rowcount>0
begin
select * from table2 where iid=0 --这样得到的才准确
delete table2 where iid=0 --从table2中删除已经插入table1的
end
commit tran --提交事务
end
go

--调用
exec p_process
林巅峰 2004-04-07
  • 打赏
  • 举报
回复
好问题解决了,散分了,
谢谢楼上的各位!
kewudemao 2004-04-07
  • 打赏
  • 举报
回复
再在上面几个大虾的SP 末尾加上 select * from table1 where iid = 0 不就行了。
林巅峰 2004-04-07
  • 打赏
  • 举报
回复
大侠们,我需要返回这条记录的,就是我需要看到这条记录的内容呀
zjcxc 2004-04-07
  • 打赏
  • 举报
回复
--处理的存储过程
create proc p_process
as
if not exists(select 1 from table1 where iid=0) --检查在table1中是否存在
begin
set xact_abort on
begin tran --用事务处理,保证数据处理成功
insert table1 select * from table2 where iid=0 --插入到table1`
if @@rowcount>0 --如果@@rowcount>0,表示table2中有符合条件的记录
delete table2 where iid=0 --从table2中删除已经插入table1的
commit tran --提交事务
end
go

--调用
exec p_process
zjcxc 2004-04-07
  • 打赏
  • 举报
回复

--处理的存储过程
create proc p_process
as
if not exists(select 1 from table1 where iid=0)
begin
set xact_abort on
begin tran
insert table1 select * from table2 where iid=0
if @@rowcount>0
delete table2 where iid=0
commit tran
end
go
pbsql 2004-04-07
  • 打赏
  • 举报
回复
CREATE PROCEDURE [dbo].[sp_1]
AS
if not exists(select * from table1 where iid=0)
if exists(select * from table2 where iid=0)
begin
insert into table1
select * from table2 where iid=0
delete from table2 where iid=0
end
solidpanther 2004-04-07
  • 打赏
  • 举报
回复
create procedure jjjj as
insert into table1 select * from table2 where iid=0
delete from table2 where iid=0
txlicenhe 2004-04-07
  • 打赏
  • 举报
回复
if not exists(select 1 from table1 where iid = 0)
begin
insert table1 select * from table2 where iid = 0
delete table2 where iid = 0
end
林巅峰 2004-04-07
  • 打赏
  • 举报
回复
国际惯例自己友情up!

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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