Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

Querying Microsoft SQL Server

I am a technology enthusiast and software developer by profession. I am developing .Net/database based enterprise applications from past 3 years.

My skills includes C# ,ASP.NET,SQL Server 2008 and MVC . My areas of interests are database development and application software development using Microsoft Technologies.

When and why you should use 1=1 in WHERE clause?

One Interviewer ask this question during interview of my friend.It is easy to answer but need some specific and to the point answer.So I try to relate it with C#.
 If you don't know  the list of conditions at compile time and it will built at run time, Then you can made a condition with “where 1=1”. and for other conditions that will affect run time, use

and  <condition>.


                StringBuilder sb = new StringBuilder();
        sb.Append("SELECT * FROM Products");  // Your query
        sb.Append(" WHERE 1=1"); // always true condition
        // append query's where clause
        if (catID != 0)
            sb.Append(" AND categoryID= {0}", catID);
        if (minPrice > 0)
            sb.Append(" AND itemPrice >= {0}", minPrice);
       SqlCommand cmd = new SqlCommand(sb.ToString(), cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        // your code to read data from dr.



Leave a comment on the original post [, opens in a new window]

Loading comments...