DECLARE @DATA TABLE
(
Id int,
Value int
)
INSERT INTO @DATA VALUES (1, 10)
INSERT INTO @DATA VALUES (2, 20)
INSERT INTO @DATA VALUES (3, 30)
INSERT INTO @DATA VALUES (4, 40)
DECLARE @TO_FILL TABLE
(
Id int,
Value int
)
INSERT INTO @TO_FILL VALUES (1, 100)
INSERT INTO @TO_FILL VALUES (3, 300)
DECLARE @METHOD int = 0
IF @METHOD = 0
BEGIN
UPDATE @DATA
SET Value = source.Value
FROM @TO_FILL source
WHERE [@DATA].Id = source.Id
END
ELSE
BEGIN
UPDATE @DATA
SET Value = source.Value
FROM @DATA destination
INNER JOIN @TO_FILL source ON destination.Id = source.Id
END
SELECT *
FROM @DATA
The idea is to update the table @DATA with the values from @TO_FILL, whenever the id matches. Whether @METHOD is set to 0 or not, this query will provide the same result.
I could understand the logic behind the block that uses the WHERE clause, which would be :
- Update table @DATA
- For each row, modify column Value
- Use the column Value from table @TO_FILL, alias source
- Do the modification whenever both columns Id match
But I have a hard time figuring the reasoning behind the second block, that uses the INNER JOIN clause. In my eyes, there are three 'temporary instances' of table : @DATA, @DATA alias destination, @TO_FILL alias source. destination and source are being joined to determine the set of rows that have to be modified (let's call it @DATA_TO_FILL), but I can't see how it is linked to the first table (@DATA). Since there are no WHERE or INNER JOIN clause between @DATA and @DATA_TO_FILL, how come it works ?