1

Using Jooq, I would like to specify the value of a field during insert as a function.

In SQL Server the equivalent query is:

insert into table (a, t) values ('foo', SYSDATETIME())

root
  • 452
  • 4
  • 8

1 Answers1

1

Mixing bind values with expressions:

Assuming you're using generated code, write this:

// Assuming this static import, as always:
import static org.jooq.impl.DSL.*;

ctx.insertInto(TABLE)
   .columns(TABLE.A, TABLE.T)
   .values(val("foo"), currentTimestamp()) // or currentLocalDateTime()
   .execute();

The VALUES() clause only has 2 overloads:

  • Accepting only bind variables
  • Accepting only expressions

It doesn't have an overload mixing both things, because there would be an exponential number of needed overloads. So the key thing to do here is to wrap your bind variables using DSL.val() explicitly.

See also this question: How do I create a Field<T> from a value T in jOOQ, explicitly?

A note on SYSDATETIME

jOOQ supports the standard SQL CURRENT_TIMESTAMP expression via DSL.currentTimestamp() and DSL.currentLocalDateTime(). If you prefer using SYSDATETIME, you can create a plain SQL template for that, or use DSL.function()

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • thanks Lukas, all my searching related to "functions" and "currentTimestamp" gave me examples of SELECTs that used DSL.field(). Just my perspective, but an example of using val() in the INSERT documentation might be useful. That was the missing link for me. – root Apr 25 '22 at 18:13
  • @root: we could add an example of val() in every single section... Anyway. People will now find this Q&A – Lukas Eder Apr 25 '22 at 21:12