Skip to content

Using a row's value within an expression/ordering (CASE/WHEN/THEN/ELSE/END expression) #1346

Answered by groue
dawilliams-gpsw asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @dawilliams-gpsw,

There is no built-in support for the general CASE WHEN THEN ELSE END expression in GRDB, but you can build your specific one:

func localizedDate(
    timeZoneOffset: some SQLExpressible,
    date: some SQLExpressible)
-> SQLExpression
{
    SQL("""
        CASE WHEN \(timeZoneOffset) IS NULL
        THEN datetime(\(date), 'localtime')
        ELSE datetime(\(date), printf('%d minutes', \(timeZoneOffset)))
        END
        """).sqlExpression
}

Usage:

// SELECT *, CASE...END AS localizedDate
// FROM ...
// ORDER BY localizedDate
let localizedDate = localizedDate(
    timeZoneOffset: Column("timeZoneOffset"), 
    date: Column("date"))

let request = try MyRecord
    

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@dawilliams-gpsw
Comment options

@groue
Comment options

groue Mar 4, 2023
Maintainer

Answer selected by dawilliams-gpsw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants