SET ANSI_NULLS ON/OFF in SQL Server

When ever we are creating or altering the SQL objects like the Stored Procedures and the User Defined Functions at that time most of us use this. Let us understand this better with an example let us create a table and insert some records,

CREATE TABLE #Demo

(

FName VARCHAR(200),

LName Varchar(200)

)

Insert #Demo values('Ravi','Shekhar')

Insert #Demo values('Isha',NULL)

Insert #Demo values('Santosh','Thakur')

 
SQL Server tends to behave differently when ever we use either
the SET ANSI_NULL ON or the OFF .

SET ANSI_NULL ON;

If the ANSI_NULL is on then the comparison with NULL value with = or <> returns false.

SET ANSI_NULLS ON

SELECT * FROM #Demo WHERE LName = NULL

SELECT * FROM #Demo WHERE LName <> NULL

The above query returns No result just because of the ANSI_NULL was ON.

In such a case we use IS NULL or IS NOT NULL.

SET ANSI_NULLS ON

SELECT * FROM #Demo WHERE LName IS NULL

SELECT * FROM #Demo WHERE LName IS NOT NULL

The Above query returns the rows with NULL/NOT NULL value.

When this setting value is ON then we need to use IS NULL or IS NOT NULL instead of the comparison operator = and <>.

SET ANSI_NULL OFF;

On the other hand if this setting value is OFF then the comparison with the NULL value using = and <> comparison operator returns TRUE.

SET ANSI_NULLS OFF

SELECT * FROM #Demo WHERE LName = NULL

SELECT * FROM #Demo WHERE LName <> NULL

If there is any mistake in the concept mentioned above. Then do Comment.

Ebook Download
View all
Learn
View all