Use the following statement to update a batch of records:
Update publish set contentid =
(Select top 1 articles. contentid from articles
Where articles. articleID = publish. objectID
)
-- Where publish. objectid = @ objectID
The premise is that the records in the publish table cannot be greater than those in the Article table. That is, the target table to be inserted cannot be inserted with null. Otherwise, an error is prompted.
There is no way to change it to a cursor:
SET NOCOUNT ON
DECLARE @ contentID int
Declare @ objectID int
Declare @ countnumber int
Set @ countnumber = 0
DECLARE publish_cursor CURSOR
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
-- Modify record
Update publish set ContentID = @ contentID where objectid = @ objectID
-- Modification ended
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)
Is there any better way?
You can also 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
The above is applicable to SQL SERVER. If it is Oracle, you can try the following methods:
Http://www.cnblogs.com/downmoon/archive/2012/11/05/2755245.html