获取CURRENT_TIMESTAMP作为ResultSet的一部分

时间:2010-11-18 08:33:03

标签: java sql sql-server identity resultset

有没有办法在除IDENTITY字段之外的Java中检索数据库生成的值?我可以轻松地从ResultSet获取IDENTITY值,但我想获取数据库生成的日期字段的值(CURRENT_TIMESTAMP)。我不想发送另一个SELECT查询来获取日期。

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

2 个答案:

答案 0 :(得分:2)

你有没有试过像

这样的东西
INSERT INTO foo (bar_date) 
OUTPUT INSERTED.bar_date
VALUES (CURRENT_TIMESTAMP)

查看OUTPUT Clause (Transact-SQL)

答案 1 :(得分:0)

假设您使用的是SQL 2005或更高版本,可以在insert语句中添加OUTPUT子句,以使其返回结果集。

我不确定要检索结果集的Java语法,但它将类似于以下内容:

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
}