问题
Given:
build.sbt
$cat build.sbt
scalaVersion := "2.11.8"
libraryDependencies += "com.typesafe.play" % "anorm_2.11" % "2.5.1"
REPL
import anorm._
val x: Option[BigDecimal] = Some(42)
val none: Option[BigDecimal] = None
// invoke Oracle function `f`
scala> SQL""" select f(#$x) from dual """.sql.statement
res0: String = " select f(Some(42)) from dual "
scala> SQL""" select f(#$none) from dual """.sql.statement
res1: String = " select f(None) from dual "
I'd like for res0
to equal: select f(42) from dual
, and for res1
to equal select f(NULL) from dual
.
How can I modify my SQL
code to fit my desired results?
I imported anorm._
, per https://stackoverflow.com/a/22531320/409976, however, it did not give my desired result.
回答1:
Using $
interpolation, just use SQL""" select f($x) from dual """
.
You can do it with #$
, but you certainly shouldn't (#$
should only be used when you can't do what you want with $
: e.g. for interpolating table or column names):
def invokeF(x: Option[BigDecimal]) = {
val xInSql = x.fold("NULL")(_.toString) // can be inlined to get even less readable
SQL""" select f(#$xInSql) from dual """
}
来源:https://stackoverflow.com/questions/40489039/using-optionbigdecimal-with-anorm