Como obtener "LAST_INSERT_ID"

Responder
williamL
Mensajes: 20
Registered for: 3 years 4 months
El Salvador

Como obtener "LAST_INSERT_ID"

Mensaje por williamL »

Buenos días:
Estoy trabajando con MariaDb y WDO y tratando de obtener el “LAST_INSERT_ID” de la inserción en una tabla que me servirá para relacionarla con otra tabla hijo de la primera. (la relación padre-hijo o Cabecera-Detalle)

He intentado de la siguiente manera y no logro obtenerlo en el ejemplo de Charly: “sql4.prg”

Código: Seleccionar todo

	o:Query( "INSERT INTO users (name, age) VALUES ('Maria "   + time() + "', '80')" )
		lnLastid1 := o:Query( "Select LAST_INSERT_ID()") 
	?  'lnLastid1 = '
	?   lnLastid1

//    de esta otra:

	o:Query( "INSERT INTO users (name, age) VALUES ('Josefa "  + time() + "', '84')" ) 
	oQryId := o:Query( "SELECT last_insert_id(id) ")
	MiId := oQryId.id
	? 'MiId = '
	?? MiId

//   y de esta otra forma:

	o:Query( "INSERT INTO users (name, age) VALUES ('Maria "   + time() + "', '80')" ,	(“Select LAST_INSERT_ID()”))
	?  'lnLastid1 = '
	?   lnLastid1

y tampoco me funciona. Me pueden sugerir que debo hacer?

Gracias.

Avatar de Usuario
ricardo arraes
Mensajes: 87
Registered for: 3 years 5 months
Brazil

Mensaje por ricardo arraes »

Hey William,

Sorry, I'm not an expert in WDO, but maybe WDO is closing the connection after the request, and reopenning it to execute your next request... so I guess your LAST_INSERT_ID() would not work as you expect...

Why don't you try something like:

Código: Seleccionar todo

SELECT id FROM table ORDER BY id DESC LIMIT 1
If your "id" is an autoincrement it should work

hope it helps you!
The work always comes before the belief

ramirezosvaldo
Mensajes: 127
Registered for: 3 years 5 months
Mexico

Mensaje por ramirezosvaldo »

Espero que este link pueda servir

Me gusto el RETURNING


https://stackoverflow.com/questions/294 ... nserted-id

Saludos
Osvaldo Ramirez

williamL
Mensajes: 20
Registered for: 3 years 4 months
El Salvador

Mensaje por williamL »

Thanks Richard:
in fact I tried doing the 3 consecutive inserts and it executes them well, I think it is not because of the closing of the connection. Also I tried your option and I can't bring up the id of the new record.

On the other hand, in a multi-user environment, I need to bring the registration id entered by my entity (user typing at that time.)
In a multi-user environment, by typing Invoices, I must obtain that id for the relationship with the invoice detail, or shipments.

*---

Gracias Ricardo:
de hecho probé haciendo los 3 insert consecutivos y los ejecuta bien, creo que no es por el cierre de la conexión. Además probé tu opción y no logro traer el id del nuevo registro.

Por otro lado en un ambiente multiusuario, necesito traer el id de registro ingresado por mi entidad (usuario digitando es ese momento.)
En un ambiente multiusuario digitando Facturas debo obtener ese id para la relación con el detalle de facturas, o los envíos.

Osvaldo: gracias también por tu aporte, pero ya había consultado en el manual de MariaDb y ese es el script recomendado. El que tu mencionas es de PostgreSQL.

En este momento se me ocurren dos opciones
:
1- Hacerlo con ModHarbour (o Mercury). Pero mi problema es que no se programar en Harbour, hasta ahora con ModHarbour estoy aprendiendo.

2- Hacerlo con HTML invocando una función de PHP tanto para guardar el registro como para obtener el id. Pero no se como invocar esa función desde modharbour.

Tal ves Charly pueda echarnos una mano porque en Tweb-Php se hacia con mucha facilidad.

williamL
Mensajes: 20
Registered for: 3 years 4 months
El Salvador

Mensaje por williamL »

Gracias Compañeros por su ayuda, la persistencia .....

Lo tengo:

Código: Seleccionar todo

		o:Query( "INSERT INTO users (name, age) VALUES ('Maria "   + time() + "', '80')" )
		lnLastid := o:Query( "Select LAST_INSERT_ID()")

		aData := o:FetchAll( lnLastid1 )

?   'aData = '
??  aData

Cristobal
Site Admin
Mensajes: 315
Registered for: 3 years 6 months
Spain

Mensaje por Cristobal »

Muy bien William
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces

Responder