在Anorm中使用`Option [BigDecimal]`?

时间:2016-11-08 14:09:47

标签: scala anorm

假设:

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 "

我希望res0等于:select f(42) from dualres1等于select f(NULL) from dual

如何修改我的SQL代码以符合我想要的结果?

我按https://stackoverflow.com/a/22531320/409976导入了anorm._,但是,它没有达到我想要的结果。

1 个答案:

答案 0 :(得分:1)

使用$插值,只需使用SQL""" select f($x) from dual """

可以使用#$执行此操作,但您当然不应该#$仅在您无法使用{{1}执行操作时使用$例如:用于插值表或列名称):

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 """
}