Update the associated table batch update

Source: Internet
Author: User
Tags join

Use the following statement when updating a batch of records:

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

If the record of the publish table cannot be greater than the record of the article, that is, the table in which you want to insert it can insert NULL, otherwise you will be prompted for an error.

There's no way to do that, change to cursors:

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 Publish P
Inner JOIN articles A 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

--Modifying records
Update publish set contentid= @contentID where objectid= @objectID
--End of modification
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 Publish P
Inner JOIN articles A on A.articleid=p.objectid
where Objectid>0 and p.contentid<> A.contentid
and (p.cellid=160 or cellid=138)
Go

--Update publish set contentid=0 where (cellid=160 or cellid=138)
--select * from Publish P where (p.cellid=160 or cellid=138)

There's no better way to do it?

You can actually do this:

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

-- select * from publish where cellid=138
-- update publish set contentid=0 where cellid=138

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.