This is a quick follow-up to part 1, with a couple more observations about dynamic parameters.
Embedded Apostrophes
Here’s one I can’t believe I forgot to mention the other day: A major ExecuteSQL headache that dynamic parameters can alleviate is the dreaded “embedded apostrophe” problem. In case you aren’t familiar with it, if your text string contains an embedded apostrophe, in standard SQL you must escape it by prepending another apostrophe, for example compare these two “standard” (non-dynamic) queries:
As you might expect, you don’t have to worry about this if you instead use a dynamic parameter… just quote the search term the way you would any FileMaker text string (i.e., in double quotes) and go about your business.
“IN” Operators
I’ve been evangelizing dynamic parameters as if they are always superior, but Stephen Dolenski recently pointed out on Friday Night Chat that when it comes to the “IN” operator, the dynamic approach may end up being more restrictive than the standard one.
As you may know, the IN operator provides a way to avoid long chains of “or” tests. For example, instead of this…
ExecuteSQL(
" SELECT MAX ( sales )
FROM customers
WHERE state = 'WA' or state = 'OR' or state = 'ID' "
; "" ; ""
)
…if you use the IN operator, the query can be streamlined, thus…
ExecuteSQL(
" SELECT MAX ( sales )
FROM customers
WHERE state IN ('WA','OR','ID') "
; "" ; ""
)
…and with dynamic parameters, it looks like this:
ExecuteSQL(
" SELECT MAX ( sales )
FROM customers
WHERE state IN ( ? , ? , ? ) "
; "" ; "" ; "WA" ; "OR" ; "ID"
)
When you just have a few choices, it’s not a big deal to go the dynamic route, but what if you are constructing the IN arguments “on the fly”, and you aren’t sure how many arguments there will be? I’ll come back to that in just a sec, but first I want to introduce a custom function that transforms a return-delimited list into an IN-friendly comma-separated list.
Based on what you saw in part 1, where dynamic parameters could do no wrong, you might think that if you had a value list, Northwest, consisting of WA¶OR¶ID, that this would work…
Let (
x = FormatListForIn ( ValueListItems ( Get ( FileName ) ; "Northwest" ) ) ;
ExecuteSQL (
" SELECT MAX ( sales )
FROM customers
WHERE state IN ( ? ) "
; "" ; "" ; x )
) // end let
…but it does not. With dynamic parameters, each item must be enumerated separately — thank you Ralph Lilienkamp for helping me understand this — so you can’t use the result of the custom function ('WA','OR','ID') as the corresponding argument for a single “?”. Meanwhile, this non-dynamic construction purrs along like a contented kitten:
Or course this is a simple use-case, and your mileage may vary, but I thought it was worth sharing, and I want to close by thanking Stephen Dolenski for bringing it up, and also Ernest Koe for helping me clarify my thinking about this.