Skip to main content

Posts

Showing posts with the label set

SQL Server 2008 - Inline Variable Assignment

Microsoft SQL Server 2008 brings in a new feature of 'Declaring and Assigning' a variable all in a single line. Earlier, while using SQL 2005 and earlier versions, we had to declare a variable before assigning it. This feature is explained in detail below. In SQL 2005 and earlier versions we had to write: Declare @age int Declare @name nvarchar(25) Declare @date date Set @age = 25 Set @name = "Garry" Set @date = GETDATE() With SQL 2008 we can combine both these statements to write Declare @age int = 25 Declare @name nvarchar(25) Declare @date @date = GETDATE() Advantage : This helps us to write less code, yet get the same functionality. Even though this feature has been available it is not being used in many projects because of backward compatibility issue. If the same code is being used on both 2005 and 2008 server we would prefer writing in a format compatible to both. Do share with us :  Would you like to use this new method? If not, why?

Why ' set ANSI_NULL ON ' while writing SP

-- Create table t1 and insert values. CREATE TABLE t1 (a INT NULL) INSERT INTO t1 values (NULL) INSERT INTO t1 values (0) INSERT INTO t1 values (1) GO When SET ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN.  -- SET ANSI_NULLS to ON and test. SET ANSI_NULLS ON GO DECLARE @varname int =  NULL SELECT * FROM t1  WHERE a = @varname  -- No output SELECT * FROM t1  WHERE a <> @varname -- No output SELECT * FROM t1  WHERE a IS NULL     -- NULL  GO When SET ANSI_NULLS is OFF, comparisons of all data against a null value evaluate to TRUE if the data value is NULL -- SET ANSI_NULLS to OFF and test. SET ANSI_NULLS OFF  GO DECLARE @varname int =  NULL SELECT * FROM t1  WHERE a = @varname  -- NULL SELECT * FROM t1  WHERE a <> @varname -- 0 , 1 SELECT * FROM t1  WHERE a IS NULL     -- NULL  GO -- Drop table t1. DROP TABLE t1