insert之前判断表是否存在该记录

on_my_way20xx 2011-11-21 01:15:41
各位大侠好,小弟又有SQL 的问题来叨扰大家了...

@ti_id,@proc_id,@mac_id 是随游标变化的变量
t_ring 表结构为(sub_ring_id,........),其中sub_ring_id为主键
t_pmpt_cp表结构为(sub_ring_id,mac_id,proc_id,ti_id)

==========================游标循环开始===================================
@ti_id,@proc_id,@mac_id 被赋值

insert into t_pmpt_cp select sub_ring_id ,@mac_id,,@proc_id,@ti_id from t_ring where 1 = 1 and ( (select COUNT(1) as num from t_pmpt_cp where sub_ring_id = sub_ring_id and proc_id = @proc_id and mac_id = @mac_id and ti_id = @ti_id )<1)




==========================游标循环结束===================================

我想在一条语句内实现,插入t_pmpt_cp表之前先判断是否存在当前记录,这种写法似乎有问题...
大家有建议吗
...全文
110 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2011-11-21
  • 打赏
  • 举报
回复
insert into
t_pmpt_cp select sub_ring_id ,@mac_id,@proc_id,@ti_id from t_ring
where
1 = 1
and
not exists
(select sub_ring_id from t_pmpt_cp where sub_ring_id = sub_ring_id
and mac_id = ,@mac_id and proc_id = @proc_id and ti_id =@ti_id)
on_my_way20xx 2011-11-21
  • 打赏
  • 举报
回复
insert into t_pmpt_cp select sub_ring_id ,@mac_id,@proc_id,@ti_id from t_ring awhere 1 = 1
and not exists
(select sub_ring_id from t_pmpt_cp where sub_ring_id = a.sub_ring_id
and mac_id = ,@mac_id and proc_id = @proc_id and ti_id =@ti_id)

综合qianjin大大的指导,最后SQL语句写成上面那样
on_my_way20xx 2011-11-21
  • 打赏
  • 举报
回复
版主大大 回帖真快! 小弟刚搞出来了

insert into t_pmpt_cp select sub_ring_id ,@mac_id,@proc_id,@ti_id from t_ring where 1 = 1
and not exists
(select sub_ring_id from t_pmpt_cp where sub_ring_id = sub_ring_id
and mac_id = ,@mac_id and proc_id = @proc_id and ti_id =@ti_id)

-晴天 2011-11-21
  • 打赏
  • 举报
回复
insert into t_pmpt_cp  select sub_ring_id ,@mac_id,,@proc_id,@ti_id  from t_ring a
where not exists(select 1 form t_pmpt_cp where id=a.sub_ring_id --假设以id列作比较,如果有ID相同则为存在
and ( (select COUNT(1) as num from t_pmpt_cp where sub_ring_id = sub_ring_id and proc_id = @proc_id and mac_id = @mac_id and ti_id = @ti_id )<1)




27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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