批量更新关联表(oracle、sql server)

发布时间:2020-10-30编辑:脚本学堂
批量更新关联表(oracle、sql server),供大家学习参考。在oracle中,目前未找到好的解决方法,暂时使用如下的方法:

批量更新关联表(oracle、sql server),供大家学习参考。
在oracle中,目前未找到好的解决方法,暂时使用如下的方法:
 

复制代码 代码示例:
update employee  set hrdeptname=
(select d.DEPTNAME from DEPARTMENT d
where ROWNUM=1 and d.deptID=employee.hrdeptID
)

SQL Server语法:
 

复制代码 代码示例:
Update employee set hrdeptname=d.DEPTNAME
from DEPARTMENT  d  inner join employee e  on e.HRDEPTID=d.DEPTID
where 1=1;

附:关联表的批量更新(SQL SERVER)

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

复制代码 代码示例:
update publish  set contentid=
(select top 1 articles.contentid from articles
where articles.articleID=publish.objectID
)
--where publish.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 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
       
            --修改记录
            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 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)

如果想用好点的方法,可以参考这样:
 

复制代码 代码示例:

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

作者:3w@live.cn