SQL根据B表的值对应更新A表

A表:inventory
字段:cinvcode、cidefine15

B表:diban
字段:PC码、系列名称

其中 A表cinvcode=B表PC码
想让 B表 字段 ‘系列名称‘的值赋给A表 字段 ’cidefine15‘

declare @cidefine15 nvarcahr(32)
select @cidefine15= cidefine15
from inventory a with (nolock)
left join  diban b with (nolock) on a.cinvcode=b.PC码
update diban set 系列名称=@cidefine15 where .......

两个表内关联再修改设置a表的数据

 

UPDATE tabA  a inner join tabB b on a.cinvcode= b.PC

set a. cidefine15=  b.系列名称

在SQL SERVER种通过创建存储过程来处理这个
首先我创建inventory和diban两个表,如下图,其中diban表代表系列名称的TypeName字段没值

img

然后创建存储过程提取inventory表中的字段然后更新到diban表中
创建代码如下


create PROCEDURE [dbo].[testProc] 

AS
BEGIN
    --定义inventory表中三个字段的参数
    declare @id int,@cinvcode varchar(50),@cidefine15 varchar(50);    
    --定义inventory表游标
    declare inventory_cursor cursor for select * from inventory;
    
    --打开游标开始读取数据,每读取一行数据都尝试对diban表做更新
    open inventory_cursor
    fetch next from inventory_cursor into  @id,@cinvcode,@cidefine15
    while @@FETCH_STATUS = 0
    begin
        update diban set TypeName=@cidefine15 where pcCode=@cinvcode
        fetch next from inventory_cursor into  @id,@cinvcode,@cidefine15
    end
    --游标处理完毕关闭并释放游标
    close inventory_cursor
    deallocate inventory_cursor 
END

img

存储过程创建完,通过在查询里使用命令exec testProc调用该存储过程实现

img