Retornar código do ultimo registro inserido

1 resposta
R

galera,

tenho esse método:

// Insere um novo registro na agenda
	public int incluir(Agenda agenda) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
		
		int resultado = 0;
		if (agenda.getCodaplicativo() !="" && agenda.getCodaplicativo() !=""){
			String SQL = "insert into agenda (CodAplicativo, CodUsuario) values  " +
				"(" + agenda.getCodaplicativo() + " , " + agenda.getCodusuario() + ")";
			ConectaBanco cb = new ConectaBanco();
			resultado = cb.ExecutaIUD(SQL);
			cb.FechaConexaoBD();
			atualizaDados(agenda);
		}
		
		return resultado;		
	}

Como eu faço para retornar o último código inserido ? estou usando SQL Server e geralmente faço assim:

INSERT INTO jobs (job_desc,min_lvl,max_lvl)
VALUES ('Accountant',12,125)
SELECT @@IDENTITY AS 'Identity'

Está correto ou existe alguma outra forma ?

1 Resposta

Spool

Você pode fazer o seguinte:

String sql = "SET NoCount ON;insert into agenda (CodAplicativo, CodUsuario) values  " +   
            "(" + agenda.getCodaplicativo() + " , " + agenda.getCodusuario() + ");SELECT scope_identity();SET NoCount OFF;";

Para entender:
SET NoCount ON; Desabilita o contador de linhas.
SELECT scope_identity(); Retorna o ultimo ID gerado pelo escopo.
SET NoCount OFF; Habilita novamente o contador de linhas.

At.

Criado 4 de novembro de 2008
Ultima resposta 4 de nov. de 2008
Respostas 1
Participantes 2