Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Select Case in Access SQL?

I have a query which includes fields named openingbalance and commissions. I would like to compute values for commissions based on openingbalance, similar to this Select Case block in Access VBA:

Select Case OpeningBalance    Case 0 To 5000         commission = 20    Case 5001 To 10000         commission = 30    Case 10001 To 20000         commission = 40    Case Else         commission = 50 End Select 

But since Access doesn't allow Select Case in a query, how can I accomplish my goal in Access SQL?

like image 618
Kelly K. Avatar asked Apr 02 '13 20:04

Kelly K.


People also ask

Does Access SQL support case?

The Case function can be used in the following versions of Microsoft Access: Access 2019, Access 2016, Access 2013, Access 2010, Access 2007, Access 2003, Access XP, Access 2000.

What is a select query in Access?

A select query is a database object that shows information in Datasheet view. A query does not store data, it displays data that is stored in tables. A query can show data from one or more tables, from other queries, or from a combination of the two.

Can we use select in Case statement SQL?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause.


1 Answers

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT     Switch(         OpeningBalance < 5001, 20,         OpeningBalance < 10001, 30,         OpeningBalance < 20001, 40,         OpeningBalance >= 20001, 50         ) AS commission FROM YourTable; 

If you want to store that calculated value to a field named commission:

UPDATE YourTable SET commission =     Switch(         OpeningBalance < 5001, 20,         OpeningBalance < 10001, 30,         OpeningBalance < 20001, 40,         OpeningBalance >= 20001, 50         ); 

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

like image 154
HansUp Avatar answered Oct 26 '22 02:10

HansUp