Damon
Damon

Reputation: 10809

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.

Upvotes: 1

Views: 449

Answers (1)

Martijn
Martijn

Reputation: 13632

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)

Upvotes: 1

Related Questions