26 May 2012

SQL Server Where 1=1

SQL Server Where 1=1

where 1=1 condition are most probably used in dynamic query in Sql Server.

where 1=1 equal to no where condition [i.e] always return the true value.

While building dynamic query some times there is no need of where condition, To handle this kind of situation this condition SQL Server Where 1=1 is used.

SET @SelectStatement = 'SELECT SomeData FROM dbo.SomeTable WHERE 1  = 1';
IF @Column1 IS NOT NULL SET @SelectStatement = @SelectStatement + ' AND Column1 = @Column1';
IF @Column2 IS NOT NULL SET @SelectStatement = @SelectStatement + ' AND Column2 = @Column2';

No comments:

Post a Comment

Comments Welcome