简体   繁体   中英

How can I combine all this into one SQL UPDATE query?

I'm trying to combine all of this into one query if it's even possible. I'm using SQLLite so I do not have stored procedures available.

The simple version of the query looks like :

UPDATE FoodIntake SET MealType = 'B' WHERE Time < LunchStrt AND Time > BreakfastStart

However Time must be derived:

SET Time = RIGHT(DateTime, 8)

and LunchStart and BreakfastStart must be brought in from a Patient table based on a parameter being passed from the program. Like so:

SELECT LunchStrt FROM Patient WHERE PatientId = :currentPatient AS LunchStrt
SELECT BrkStrt FROM Patient WHERE PatientId = :currentPatient AS BrkStrt

I imagine I can at last start by swapping Time for RIGHT(DateTime, 8):

UPDATE FoodIntake SET MealType = 'B' WHERE RIGHT(DateTime, 8) < LunchStrt AND RIGHT(DateTime, 8) > BreakfastStart

But I am not sure the proper syntax for bringing in LunchStrt and BrkStrt from the Patient table inside an update if it's possible.

A few notes:

  • SQLite doesn't have a RIGHT function, but you can use the substr function and pass a negative start position.
  • SQLite does support the BETWEEN ... AND ... ternary operator, so you could write WHERE substr(DateTime, -8) BETWEEN BreakfastStart AND LunchStrt
  • SQLite also supports scalar subqueries , so you can use those to retrieve the specific values you're looking for

Combine those three options, and you could write this:

UPDATE FoodIntake 
   SET MealType = 'B' 
 WHERE substr(Time, -8) 
        BETWEEN (SELECT BrkStrt FROM Patient WHERE PatientId = :currentPatient)
            AND (SELECT LunchStrt FROM Patient WHERE PatientId = :currentPatient)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM