SQLInterpolation with dynamic table name

356 views
Skip to first unread message

黃澤熹

unread,
May 27, 2015, 1:38:03 PM5/27/15
to scalikejdbc...@googlegroups.com
I have several tables divided by year, tab_2014, tab_2015

I try to construct sql command as below.

val tab_name = "[AQMSDB].[dbo].[Tab_" + DateTime.now.getYear + "]"
Logger.info("tab_name:" + tab_name)
    
    sql"""
      SELECT TOP 1 M_DateTime
      FROM ${tab_name}
      ORDER BY M_DateTime  DESC
      """.map { r=>r.timestamp(1) }.single.apply

During execution, I got an error from Microsoft SQL JDBC driver. 
It said I must declare a table variable.
I am confused why I need to declare a tab variable to make it a dynamic sql.
After all, scalikeJDBC is only using string interpolation.

Any work around or any suggestion?
Thank you



黃澤熹

unread,
May 27, 2015, 1:42:51 PM5/27/15
to scalikejdbc...@googlegroups.com
By the way, I try the following workaround and it failed as well.

var sql_cmd = s"""
SELECT TOP 1 M_DateTime
      FROM ${tab_name}
      ORDER BY M_DateTime  DESC
"""
sql"""
${sql_cmd}
"""......

黃澤熹於 2015年5月28日星期四 UTC+8上午1時38分03秒寫道:

Kazuhiro Sera

unread,
May 27, 2015, 8:47:15 PM5/27/15
to 黃澤熹, scalikejdbc...@googlegroups.com
Use SQLSyntax.createUnsafely.

val tableName =
SQLSyntax.createUnsafely(s"${x}.${y}.Tab_${DateTime.now.getYear}")
> --
> You received this message because you are subscribed to the Google Groups
> "ScalikeJDBC Users Group" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to scalikejdbc-users...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

黃澤熹

unread,
May 28, 2015, 10:57:09 AM5/28/15
to scalikejdbc...@googlegroups.com, karate...@gmail.com
Thank you so much! 

Kazuhiro Sera於 2015年5月28日星期四 UTC+8上午8時47分15秒寫道:
Reply all
Reply to author
Forward
0 new messages