Where conditions ignoring parenthesis during execution.

SQL 2016 Where statement seems to be ignoring parenthesis,  I am trying to capture work transactions for for a day that has three shifts.  The day starts on 02/14 at 6:00 am and ends at the end of third shift on 2/15 at 6:00 am.  The database does not use datetime but rather has it broken into two separate fields.  When I execute it I get no results.  If I take out the time portion of the selection, I get all of the transactions for both days.  Any suggestions?  Here is the statement:

where ((date_work_trx >= '2018-02-14' and time_work_trx > 060000) and (date_work_trx <= '2018-02-15' and time_work_trx <= 060000))
Paul PingelIT ManagerAsked:
Who is Participating?
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
where 
  (date_work_trx > '2018-02-14' or date_work_trx = '2018-02-14' and time_work_trx > 060000)
and
  (date_work_trx < '2018-02-15' or date_work_trx = '2018-02-15' and time_work_trx <= 060000)

Open in new window

0
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
You fail in the time portion, because one condition only allows for time later than 0600, the other earlier than or equal to 0600. A common mistake.
For the lower boundary, you need to check for greater as the date, or equal to the date and greater than 0600 for the time. And similar for the upper boundary.
0
 
Vitor MontalvãoConnect With a Mentor MSSQL Senior EngineerCommented:
When you work only with AND the parenthesis aren't needed at all. If I rewrite your WHERE clause like this you might understand it better:
where ((date_work_trx >= '2018-02-14' and date_work_trx <= '2018-02-15' ) and (time_work_trx > 060000 and time_work_trx <= 060000)

Open in new window


Your issue is that you don't have the time stored with the date field and that's making the filter to be more complex to write. If you can have a field to store both date and time then your query will be more simple:
where date_work_trx > '2018-02-14 06:00:00' and date_work_trx <= '2018-02-15 06:00:00'

Open in new window

0
 
Paul PingelIT ManagerAuthor Commented:
Thank you for your help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.