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