Null value in SQL statement _mssql

Source: Internet
Author: User
I wrote this code today.
Copy Code code as follows:

DECLARE @atr NVARCHAR (20)
SET @atr = NULL

IF (@atr = NULL)
BEGIN
PRINT 1
End
Originally wanted to print out 1. But no. Modify the code as follows:

DECLARE @atr NVARCHAR (20)
SET @atr = NULL

IF (@atr is NULL)
BEGIN
PRINT 1
End

This will print out the correct 1.
Then you have made the following changes to the IF statement to modify the
Copy Code code as follows:

IF (null = NULL)
BEGIN
PRINT 1
End

Results: 1 is not printed
From this we can conclude that the null value in the SQL statement and any values are not equal when doing "=" operations. The judgment of whether to use ' is null ' to make a null value.
We can also use function ISNULL (@str, 0) = 0来 to determine whether a variable is a null value.
Small problem, record, strengthen memory, good at summarizing, do not walk long way.

================================================================================

Added: NULL and "+" operators.

"+" can be used to do string concatenation, but also to do addition operations, then null value and string to do "+" what would be the result? I wrote the following validation program:
  
Copy Code code as follows:


DECLARE @str NVARCHAR (200)
DECLARE @str1 NVARCHAR (200)
DECLARE @str2 NVARCHAR (200)

SET @str = NULL
SET @str1 = ' look pretty '
SET @str2 = @str + @str1

PRINT @str2

As a result, nothing has been printed out, why? Let's test @str2 what's the value now?
IF (@str2 is NULL)
PRINT 1
The result prints out 1, so we can guess null and any type doing "+" result is still a null value
  
Then write a null and int type to do "+" validator:
Copy Code code as follows:

DECLARE @num INT
DECLARE @num1 INT
DECLARE @num2 INT

SET @num = 1
SET @num1 = 2
SET @num2 = @num + @num1
PRINT @num2

The result prints out 3, replacing the red bold part with the SET @num = NULL, and what is the result? Try it yourself, haha.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.