Wednesday, March 7, 2012

getting last ID MSSQLServer

Hi netpeople.
I have got a problem with setting parameters to a statement. I would
like get the last inserted id of a table.
The SQL statement for this on mssqlserver is:
SELECT IDENT_CURRENT(<tablename>) AS <idfieldname>
I use a PrepareStatement:
SELECT IDENT_CURRENT(?) AS ?
How do I set this parameter to the tablename and the idfieldname?
I tried with:
PreparedStatement oStmt = null;
oStmt =
m_oConn.prepareStatement(JDBCStmt.CBP_RETURNINTERF ACE_UPDATE_CONTAINER);
oStmt.setString(1, sTable);
oStmt.setString(2, sField);
But with this implementation, the executeQuery() fails.
Special Thanks for your help.
Oliver Hirschi
http://www.FamilyHirschi.ch
Oliver Hirschi wrote:

> Hi netpeople.
> I have got a problem with setting parameters to a statement. I would
> like get the last inserted id of a table.
> The SQL statement for this on mssqlserver is:
> SELECT IDENT_CURRENT(<tablename>) AS <idfieldname>
> I use a PrepareStatement:
> SELECT IDENT_CURRENT(?) AS ?
> How do I set this parameter to the tablename and the idfieldname?
> I tried with:
> PreparedStatement oStmt = null;
> oStmt =
> m_oConn.prepareStatement(JDBCStmt.CBP_RETURNINTERF ACE_UPDATE_CONTAINER);
> oStmt.setString(1, sTable);
> oStmt.setString(2, sField);
> ----
> But with this implementation, the executeQuery() fails.
> Special Thanks for your help.
Hi. It can't work that way. Parametners are only really for *data* values,
that could be plugged into a precompiled query plan. If you try to have
the table name as a parameter, it completely alters what would be a plan.
Just do this:
Statement s = oConn.createStatement();
ResultSet rs = s.executeQuery("SELECT IDENT_CURRENT(" + sTable + ") AS " + sField );
Joe Weinstein at BEA

No comments:

Post a Comment