我在SQL Server中有3个完全相同的表。我正在尝试编写一个存储过程,以从2个表中获取2列的值,并用差异更新第3个表。这是3个表:
我正在传递rfds_processing_id。它类似于订单号,包含多行,因此必须在rfds_processing_id,类型,扇区和位置上进行匹配。
我需要匹配3个表中的每一行,然后从Final.qty中减去Current.qty的值,并用差异更新Proposed.qty。它还需要使用Final.model的值更新Proposed.model(当Proposed.qty> 0时)。当前,它正在将每一行设置为相同的值。我假设我需要遍历所有行。那应该是什么样的?
ALTER PROCEDURE [dbo].[CalculateProposedAntennas]
(
@rfds_processing_id uniqueidentifier = null,
@id uniqueidentifier OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
UPDATE P
SET qty = (F.qty - C.qty) , model = F.model
FROM Proposed_Antenna P
INNER JOIN Final_Antenna F
ON P.rfds_processing_id = F.rfds_processing_id
INNER JOIN Current_Antenna C
ON F.rfds_processing_id = C.rfds_processing_id
WHERE
F.rfds_processing_id = C.rfds_processing_id
AND F.sector = C.sector
AND F.type = C.type
AND F.position = C.position
RETURN
END
答案 0 :(得分:0)
以下查询应执行您想要的操作:
ALTER PROCEDURE [dbo].[CalculateProposedAntennas]
(
@rfds_processing_id uniqueidentifier = null,
@id uniqueidentifier OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
UPDATE P
SET P.qty = F.qty - C.qty
,P.model = CASE WHEN Proposed.qty > 0 THEN F.model ELSE NULL END
FROM Proposed_Antenna P
INNER JOIN Final_Antenna F
ON F.rfds_processing_id = P.rfds_processing_id AND F.sector = P.sector AND F.type = P.type AND F.position = P.position
INNER JOIN Current_Antenna C
ON C.rfds_processing_id = P.rfds_processing_id AND C.sector = P.sector AND C.type = P.type AND C.position = P.position
RETURN
END
我强烈建议您在所有三个表中创建一个[UID]列-可以按以下方式生成唯一标识符大小写,所生成的键是varbinary
类型的键,这远胜于字符串比较加入
select [UID] = HashBytes('MD5',rfds_processing_id+type+sector+position)