UPDATE SOTemp
SET SequenceNo = SOHD.SequenceNo
FROM SalesOrderTemp AS SOTemp
INNER JOIN vSO_SalesOrderHistoryDetail AS SOHD
ON SOTemp.SONo = SOHD.SalesOrderNo
AND SOTemp.LineKey = SOHD.LineKey
Obviously this with limited knowledge of your schema so please don't run without confirming.
UPDATE O
SET O.SequenceNo = (
SELECT TOP 1 D.SequenceNo
FROM vSO_SalesOrderHistoryDetail D
WHEREO O.SONo = D.SalesOrderNo
AND O.LineKey = D.LineKey
ORDER BY D.SomeDateColumn DESC
)
FROM SalesOrderTemp O;
UPDATE O
SET O.SequenceNo = (
SELECT TOP 1 D.SequenceNo
FROM vSO_SalesOrderHistoryDetail D
WHEREO O.SONo = D.SalesOrderNo
AND O.LineKey = D.LineKey
ORDER BY D.SequenceNo DESC
)
FROM SalesOrderTemp O;
-- Setup.
-- IMPORTANT: Your primary key and the candidate keys MUST exist.
DECLARE @SalesOrderTemp TABLE (
SequenceNo INT ,
SONo INT ,
LineKey INT
);
DECLARE @vSO_SalesOrderHistoryDetail TABLE (
SequenceNo INT ,
SalesOrderNo INT ,
LineKey INT
);
-- Sample data.
--INSERT INTO @SalesOrderTemp () VALUES (),(),();
--INSERT INTO @vSO_SalesOrderHistoryDetail () VALUES (),(),();
-- Modify data.
UPDATE O
SET O.SequenceNo = ( SELECT TOP 1 D.SequenceNo
FROM @vSO_SalesOrderHistoryDetail D
WHERE O.SONo = D.SalesOrderNo
AND O.LineKey = D.LineKey
ORDER BY D.SequenceNo DESC )
FROM @SalesOrderTemp O;
-- Final output.
SELECT *
FROM @SalesOrderTemp SOT;
SELECT *
FROM @vSO_SalesOrderHistoryDetail;
('0011139', 'Service', '010 - order entry', 'Y', '000006'),
('0011139', 'Service', '010 - order entry', 'N', '000006')
INSERT INTO SalesOrderTemp ( SONo ,
OrderType ,
OrderStatus ,
CancelledLine ,
LineKey ,
ChangeDate )
VALUES ( '0011139', 'Service', '010 - order entry', 'N', '000001', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'Y', '000002', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'N', '000003', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'N', '000004', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'Y', '000005', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'Y', '000006', '2021-05-01' ) ,
( '0011139', 'Service', '010 - order entry', 'N', '000006', '2021-05-02' );
Now we could pick the correct one based on the date. Cause the relevant candidate key for your problem is (SONo, LineKey, ChangeDate).