PRB: Assignment of NULL Value to Local Variable in SQLLast reviewed: April 25, 1997Article ID: Q63212 |
The information in this article applies to:
- Microsoft SQL Server version 4.2 for OS/2 - Microsoft SQL Server version 4.2
SYMPTOMSSuppose a table named "test" has columns named "a" and "b", where the highest value of "a" is 2. "@a" is assigned a value in the normal way, as follows:
declare @a int select @a=100 select @a=b from test where a=52 select @aIt is expected that this query will return NULL because "a" is never 52. However, the query returns 100, which is the number that was first assigned to it. If the third line of the above query is replaced with the following line, NULL is returned as expected:
select @a=(select b from test where a=52) CAUSEIn the example listed above, the SELECT statement returns zero rows. Because there is no value of "b" returned from the query, SQL Server treats the previous value of @a (100) as the "default value" to use. This is the reason it does not return NULL as expected.
WORKAROUNDThis question raises the issue of the different ways SQL Server treats NULL expressions. To answer the question of why the assignment of a value to a local variable works differently when the value is NULL, the following test was performed using the example listed above:
The difference between this test and the test listed above is the "value" of "b" returned from the query. The second SELECT statement is needed so that the return value of the "entire expression" can be obtained, which is NULL, rather than the return value of "b".
|
Additional query words: Transact-SQL Windows NT
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |