产品表
产品仓库表
是否可以将Primary Warehouse和Secondary Warehouse数据复制到Product warehouse表并使用相应的Id更新Product表?
对于每个产品,我将在Warehouse表中以2行结束。
感谢。
答案 0 :(得分:0)
如果我理解你的问题,这是一个解决方案
declare @Product as table (
[Id] int identity
,[Product Name] varchar(50)
,[Primary Warehouse] varchar(50)
,[Secondary Warehouse]varchar(50)
,[PrimaryWarehouseId] int
,[SecondaryWarehouseId] int
)
declare @ProductWarehouse as table(
[Id] int identity
,[Warehouse Name] varchar(50)
)
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P01', 'W1' , '101')
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P02', 'W1' , '104')
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P03', 'W2' , '102')
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P04', 'W3' , '101')
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P05', 'W4' , '103')
insert @Product ([Product Name], [Primary Warehouse] , [Secondary Warehouse]) Values ('P06', '101' , 'W2')
insert @ProductWarehouse ([Warehouse Name] ) select distinct [Primary Warehouse] from @Product P where not exists (SELECT 1 FROM @ProductWarehouse pw where p.[Primary Warehouse] = pw.[Warehouse Name])
insert @ProductWarehouse ([Warehouse Name] ) select distinct [Secondary Warehouse] from @Product P where not exists (SELECT 1 FROM @ProductWarehouse pw where p.[Secondary Warehouse] = pw.[Warehouse Name])
select * from @Product
select * from @ProductWarehouse
update p
set [PrimaryWarehouseId] = pw.Id
from @Product p
inner join @ProductWarehouse pw
on
p.[Primary Warehouse] = pw.[Warehouse Name]
update p
set [SecondaryWarehouseId] = pw.Id
from @Product p
inner join @ProductWarehouse pw
on
p.[Secondary Warehouse] = pw.[Warehouse Name]
select * from @Product
产品表
Id Product Name Primary Warehouse Secondary Warehouse PrimaryWarehouseId SecondaryWarehouseId
----------- ------------- ------------------ -------------------- ------------------ --------------------
1 P01 W1 101 NULL NULL
2 P02 W1 104 NULL NULL
3 P03 W2 102 NULL NULL
4 P04 W3 101 NULL NULL
5 P05 W4 103 NULL NULL
产品仓库表
Id Warehouse Name
----------- ---------------
1 101
2 W1
3 W2
4 W3
5 W4
6 102
7 103
8 104
最终产品表
Id Product Name Primary Warehouse Secondary Warehouse PrimaryWarehouseId SecondaryWarehouseId
----------- -------------- ------------------- --------------------- ------------------ --------------------
1 P01 W1 101 2 1
2 P02 W1 104 2 8
3 P03 W2 102 3 6
4 P04 W3 101 4 1
5 P05 W4 103 5 7
6 P06 101 W2 1 3