Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 2=2

Author  Topic 

seeker62
Starting Member

40 Posts

Posted - 2012-11-12 : 15:37:43
This is very basic I know but when 2=2 is found in the where clause what does it mean.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-11-12 : 15:58:41
2=2 evaluates to TRUE, so it has no effect on the query.

Usually people do that when they want to construct a query programmatically.
If you start with 1=1 or 2=2, then all the additional clauses that you may want to add can be prefixed with an AND. For example:

SELECT
col1,col2
FROM
SomeTable
WHERE
1 = 1
AND StateCode = 'CT' --- dynamically added sections
AND ZipCode = '06901'
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-11-17 : 03:58:53
You see that kind of code only when dynamic sql is used and the expressions in the where clause are added based on condition. But in most cases you can avoid it by using conditional where clause like below

WHERE
(col1=@param and @flag=1)
or
(col2=@param and @flag=2)
or
.
.
.

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -