Sunday, 21 August 2022

An SQL tip for comparisons

I want to describe a technique that I found a few days ago ('necessity is the mother of invention'), but I don't really know how to title it. I had a procedure that found work orders, but only those connected to customer orders. This requires the condition SERIAL.ORDI > 0. Someone else wanted the same report, but for work orders that are not connected to customer orders, namely SERIAL.ORDI = 0. I know how to use a flag in order to change a condition, but this always assumes that the comparison operator (>, =) is the same - but it isn't in this case.

I found a solution, although I am fairly certain that there are other ways of doing this. Let's say that :$.FLG = 'Y' if the user wants only work orders connected to customer orders. My solution converts the comparison operator into BETWEEN in the following manner:

GOTO 1 WHERE :$.FLG = 'Y'; :FROM = 0; :TO = 0; GOTO 2; LABEL 1; :FROM = 1; :TO = 0; SELECT MAX (ORDI) INTO :TO FROM ORDERITEMS; LABEL 2; SELECT ....... WHERE SERIAL.ORDI BETWEEN :FROM AND :TO ....
When :$.FLG <> 'Y', the users wants only work orders not connected, so FROM and TO will be zero. Otherwise the values are 1 and max (ordi) - guaranteed to work. Had the request been for work orders that might be connected to a customer order, then FROM would have been redundant: it would be 0 in both cases.

No comments:

Post a Comment