Everyday I learn something new, it seems 🙂 Can someone please explain to me the rationale behind the following code behavior:
DECLARE @A INT
SET @A = 15
SET @A = (SELECT ValueThatDoesntExist FROM dbo.MyTable WHERE MyColumn = 'notfound')
SELECT @A
-- Rsultset is NULL
SET @A = 15
SELECT @A = ValueThatDoesntExist FROM dbo.MyTable WHERE MyColumn = 'notfound'
SELECT @A
-- Resultset is 15
From what I see, SET changes the value of the variable if the resultset is NULL, while SELECT doesn’t. Is this normal ANSI behavior or is it T-SQL specific?
Of, course, if I do SELECT @A = NULL, the assignment happens correctly.
The first version sets A to the result of a query:
Basically the
selectin in scalar context, and if it doesn’t find a row, it evaluates tonull.The second version sets A for each row in the result set:
Since there are no rows, A is never assigned to. Another example:
This will assign 3 values to
@a. The last one assigned is3, so that’s what the query prints.