有谁知道我可以用什么Spring Jdbc模板方法来执行这个'upsert',或者另外一种方法也可以在一次数据库调用中执行操作?
UPDATE jasper_report SET Uri = 'update' WHERE ReportId = 99;
IF @@ROWCOUNT = 0 AND Exists(Select 1 FROM report Where Id = 99)
BEGIN
INSERT INTO jasper_report (ReportId, Uri) VALUES (99, 'insert')
END;
答案 0 :(得分:3)
原来我很接近,但忘记了一步。
我不得不将查询本身更改为:
BEGIN
UPDATE jasper_report SET Uri = ? WHERE ReportId = ?
IF @@ROWCOUNT = 0 AND EXISTS(SELECT 1 FROM report WHERE Id = ?)
BEGIN
INSERT INTO jasper_report (ReportId, Uri) VALUES (?, ?)
END
END
然后在我的Dao中只需要使用Spring's JdbcTemplate update method。它看起来像这样:
@Repository("jasperReportsDao")
public class JasperReportsDaoImpl extends JdbcTemplate implements JasperReportsDao {
@Override
public void saveJasperReport(JasperReport report) {
// If a record already exists, do an update, otherwise, do an insert
int rowsAffected = this.update(UPSERT_JASPER_REPORT, new Object[] { report.getUri(), report.getId(),
report.getId(), report.getId(), report.getUri()} );
if(log.isDebugEnabled()) { log.debug("Rows affected: " + rowsAffected); }
}
}
答案 1 :(得分:1)
不应该是Not Exists
?
无论如何,我认为没有Not Exists
它会正常工作,因为@@ROWCOUNT
已经提供了这些信息:
UPDATE jasper_report SET Uri = 'update' WHERE ReportId = 99;
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO jasper_report (ReportId, Uri) VALUES (99, 'insert')
END;