I have the following sql
DECLARE @tmpSelectedData TABLE -- table variable
(SlNo INT IDENTITY(1,1) PRIMARY KEY
,dataID INT NULL
,ValID INT NULL
,DdrID INT NULL
,InrID INT NULL
,IprID INT NULL)
-- inserting into table variable
INSERT INTO @tmpSelectedData(dataID)
SELECT
SQ.dataID
FROM
@SelectedQuestions SQ
-- Update the table variable with some values
tblData
dataID,ValID,DdrID,InrID,IprID
1- 2- 3 - 4- 5
2- 7- 4 - 5- 8
3- 8- 2 - 4- 3
4- 0- 1 - 2- 5
@SelectedData
dataID
2
3
4
@tmpSelectedData
dataID,ValID,DdrID,InrID,IprID
2-
3-
4-
UPDATE @tmpSelectedData
SET IprID = D.dataID,
DdrID = D.DdrID,
InrID = D.InrID
FROM tblData D
INNER JOIN @SelectedData SD ON SD.dataID = D.dataID
Using this query, all the rows of @tmpSelectedData will be updated with the value which is corresponding to the first row of tblData
Expected result in @tmpSelectedData:
dataID,ValID,DdrID,InrID,IprID
2- 7- 4 - 5- 8
3- 8- 2 - 4- 3
4- 0- 1 - 2- 5
Actual result in @tmpSelectedData:
dataID,ValID,DdrID,InrID,IprID
2- 7- 4 - 5- 8
3- 7- 4 - 5- 8
4- 7- 4 - 5- 8
it will update only with the first value
UPDATE @tmpSelectedData
SET dataID = D.dataID,
DdrID = D.DdrID,
InrID = D.InrID
FROM tblData D
INNER JOIN @tmpSelectedData SD ON SD.IprID = D.IprID
When I changed it to @tmpSelectedData from @SelectedData (second query), it will works and update as the expected result.
What is the difference between two queries ?
This is one of the issues with the
UPDATE ... FROMsyntax – if it, in effect, attempts to update the same row multiple times, the end result will be one of those updates, but which one is indeterminate – and it doesn’t give an error or warning message when this happens.What you have in your first
UPDATEquery is aFROMclause that doesn’t reference the table to be updated at all – it’s effectively an uncorrelated query, such that the entire resultset generated by theFROMclause applies to all rows in the target table. One row (in this case, the "first", although that is ill defined) has been the row to "win" the update (it should be noted, equally, that there’s no guarantee that the same row will "win" against each row in the table being updated).In your second query, because the table to be updated is referenced in the
FROMclause: