开发者

Get CURRENT_TIMESTAMP as part of ResultSet

开发者 https://www.devze.com 2023-01-26 04:54 出处:网络
is there any way of retrieving database generated values in Java other than IDENTITY fields? I can easily get IDENTITY values from a ResultSet, but I\'d like to get the value of a date field which has

is there any way of retrieving database generated values in Java other than IDENTITY fields? I can easily get IDENTITY values from a ResultSet, but I'd like to get the value of a date field which has been generated by the database (CURRENT_TIMESTAMP). I prefer not to send another SELECT query to get the date.

statement = connection.prepareStatement("INSERT INTO foo (bar_date) VALUES (CURRENT_TIMESTAMP)");
ResultSet generatedKey = statement.getGeneratedKeys();
while开发者_如何转开发 (generatedKey.next()) {
  // read the key..., this unfortunately only returns IDENTITY columns.
}


Have you tried something like

INSERT INTO foo (bar_date) 
OUTPUT INSERTED.bar_date
VALUES (CURRENT_TIMESTAMP)

Have a look at OUTPUT Clause (Transact-SQL)


Assuming you're using SQL 2005 or later, you could add an OUTPUT clause to your insert statement to have it return a result set.

I'm not sure of the Java syntax to retrieve the resultset, but it would be something like the following:

statement = connection.prepareStatement("INSERT INTO foo OUTPUT inserted.id, inserted.bar_date (bar_date) VALUES (CURRENT_TIMESTAMP)"); //guessing the name of the id column
ResultSet returnSet = statement.execute(); // or however you do this
while (resultset.next()) {
  // resultset will have two columns - id and bar_date
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号