Thursday, May 2, 2019

Optional condition in where clause


We mostly used to write select statement with where clause. Sometime, we may need to handle optional condition in the where clause. If the variable having value then we need to fetch only that record otherwise, we need to fetch all records. In this case we need to use optional condition in where clause.

For example, in the report, if user selected the customer account number in the report dialog box, then need to display the selected customer. If the user is not selected any customer account then we need to display all customers in the report.

Sometimes, we will write the condition like below

If(_accountNum == “”)
{
   While select * from custTable
   {
   }
}
Else
{
   While select * from custTable
   where custTable.AccountNum == _accountNum
   {
   }
}

But we can optimize the code like below

While select * from custTable
where (custTable.AccountNum == _accountNum || _accountNum == “”)
{
}

It might be old but, I believe it will be helpful to someone J

No comments :

Post a Comment