PRB: Assignment of NULL Value to Local Variable in SQL

Last reviewed: April 25, 1997
Article ID: Q63212

The information in this article applies to:

  - Microsoft SQL Server version 4.2 for OS/2
  - Microsoft SQL Server version 4.2

SYMPTOMS

Suppose 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 @a

It 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)

CAUSE

In 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.

WORKAROUND

This 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:

  1. Place the test values of "a" and "b" in the table. For example: a=52, and b=NULL.

  2. Set @a = 100, and perform the following select statement:

          select @a=b from test where a=52
    

The variable @a is successfully assigned as NULL.

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
Keywords : kbother SSrvServer SSrvTrans SSrvWinNT
Version : 4.2 | 4.2
Platform : OS/2 WINDOWS
Issue type : kbtshoot


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: April 25, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.