关联表的批量更新(downmoon)

本文介绍了一种使用SQL更新记录的方法,包括直接更新与游标方式,并提供了具体的SQL语句实例,适用于publish表与articles表间的数据同步场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在更新一批记录时使用如下语句:


update publish set contentid =
(
select top 1 articles.contentid from articles
where articles.articleID = publish.objectID
)
-- wherepublish.objectid=@objectID


前提是:publish表的记录不能大于Article的记录,即要插入的目标表中不能插入null,否则会提示错误。

后来没办法,改为游标:



SET NOCOUNT ON
DECLARE @contentID int
declare @objectID int
declare @countnumber int
set @countnumber = 0
DECLARE publish_cursor CURSOR FOR
select a.contentid,a.articleID from publishp
inner join articlesa on a.articleID = p.objectID
where objectid > 0 and p.contentid <> a.contentid
and (p.cellid = 160 or cellid = 138 )
OPEN publish_cursor

FETCH NEXT FROM publish_cursor
INTO @contentID , @objectID

WHILE @@FETCH_STATUS = 0
BEGIN
print @contentID
print @objectID

-- 修改记录
update publish set ContentID = @contentID where objectid = @objectID
-- 修改结束
FETCH NEXT FROM publish_cursor into @contentID , @objectID

END
CLOSE publish_cursor
DEALLOCATE publish_cursor

GO

select p.publishid,p.contentid,a.contentid,p.objectID,a.articleID from publishp
inner join articlesa on a.articleID = p.objectID
where objectid > 0 and p.contentid <> a.contentid
and (p.cellid = 160 or cellid = 138 )
go

-- updatepublishsetcontentid=0where(cellid=160orcellid=138)
--
select*frompublishpwhere(p.cellid=160orcellid=138)


在没有更好的办法呢?
其实还可以这样:

update publish set contentid = a.contentid
from articlesa inner join publishp on p.objectID = a.articleID
where cellid = 138

-- select*frompublishwherecellid=138
--
updatepublishsetcontentid=0wherecellid=138

邀月注:本文版权由邀月 和优快云共同所有,转载请注明出处。
助人等于自助! 3w@live.cn

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值