Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Conexión con bases de datos (https://www.clubdelphi.com/foros/forumdisplay.php?f=2)
-   -   Problema con ApplyUpdate ClientDataSet y Autonumérico (https://www.clubdelphi.com/foros/showthread.php?t=91258)

raul_toled 14-12-2016 17:11:34

Problema con ApplyUpdate ClientDataSet y Autonumérico
 
Buenas.... necesito solventar este enigma. Tengo una conexión DBExpress con los siguientes componentes

TSQLConnection: Conexión con SQL Server
TSQLQuery: con la consulta a una tabla Maestra con una columna AUTOINCREMENTABLE
TDataSetProvider: Asociado al TSQLQuery
TClientDataSet: Asociado al TDataSetProvider
TDataSet: Asociado al TClientDataSet (para conectar componentes y grid)

El problema es el siguiente, tengo una tabla Maestra con el AUTOINCREMENTABLE y una tabla Hija que tiene una ForeingKey de la Maestra

Cuando realizo el insert de la Maestra hago lo siguiente

1.- Abro una Transacción
2.- ClientDataSet1.CheckBrowseMode
3.- ClientDataSet1.ApplyUpdates(0)
4.- Intento recuperar el valor de Identidad insertado (con el select scope_identity()) Aquí tengo el problema
5.- Después tengo que insertar en la tabla detalle (utilizando el id obtenido de la tabla anterior)
6.- Commit o Rollback de la transacción

Necesito rescatar el ID de dicha tabla (autonumerico) para después realizar varios insert en la tabla detalle.

Después del ApplyUpdates hago una consulta directa al SQL Server "SELECT SCOPE_IDENTITY()" para obtener el ultimo valor de identidad insertado pero me devuelve NULL

¿Cómo podría recuperar ese valor del autonumérico recién insertado?

He probado ha hacerlo en el AfterUpdateRecord, AfterApplyUpdate del DataSetProvider, del ClientDataSet..... y nada... no doy con la tecla

¿Alguna idea de como hacerlo y obtener ese valor autonumérico?

Gracias

luisgutierrezb 14-12-2016 19:19:14

Bueno de la página http://blog.sqlauthority.com/2007/03...ity-of-record/

a grandes razgos, debes utilizar @@identity

SELECT @@IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

raul_toled 15-12-2016 08:06:09

Si, lo que pasa que la tabla tiene desencadenadores que graba una tabla de log (con otro autonumérico), entonces el @@IDENTITY me devuelve el ID de la tabla de log y no el del propio registro insertado. Tiene migas la cosa....

Cita:

Empezado por luisgutierrezb (Mensaje 511772)
Bueno de la página

a grandes razgos, debes utilizar @@identity

SELECT @@IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.


olbeup 15-12-2016 08:36:37

Cita:

Empezado por raul_toled (Mensaje 511790)
Si, lo que pasa que la tabla tiene desencadenadores que graba una tabla de log (con otro autonumérico), entonces el @@IDENTITY me devuelve el ID de la tabla de log y no el del propio registro insertado. Tiene migas la cosa....

Hola raul_toled,

Lo que yo hago es guardarme el @@IDENTITY en una variable para mas tarde utilizarla donde se necesite.

eje.

Código SQL [-]
DECLARE
  @idClientNew  int
  ,@idLogNew    int

INSERT INTO Clientes (NOMBRE, DIRECCION, ETC) VALUES ('Yo', 'Aqui', 'etc...')

SET @idClientNew = @@IDENTITY

INSERT INTO LogDB(CAMPO1, CAMPO2) VALUES ('BLABLA', 'MAS BLA BLA')

SET @idLogNew = @@IDENTITY

INSERT INTO ClientesDetalles(CAMPO1, CAMPO2, CAMPOX, CLIENTEID) VALUES ('BLA BLA', 'MAS', 'Y MAS BLA BLA', @idClientNew)
Esto es lo que tienes que hacer, así lo hago yo y ningún problema.

Un Saludo.

raul_toled 15-12-2016 10:55:43

Muchas Gracias... pero te cuento...

No estoy directamente sobre SQL

Utilizo el ApplyUpdates del ClientDataSet (Monta el insert automáticamente)

La tabla Maestra (tu cliente) tiene un desencadenador que graba un log automáticamente




Cita:

Empezado por olbeup (Mensaje 511791)
Hola raul_toled,

Lo que yo hago es guardarme el @@IDENTITY en una variable para mas tarde utilizarla donde se necesite.

eje.

Código SQL [-]
DECLARE
  @idClientNew  int
  ,@idLogNew    int

INSERT INTO Clientes (NOMBRE, DIRECCION, ETC) VALUES ('Yo', 'Aqui', 'etc...')

SET @idClientNew = @@IDENTITY

INSERT INTO LogDB(CAMPO1, CAMPO2) VALUES ('BLABLA', 'MAS BLA BLA')

SET @idLogNew = @@IDENTITY

INSERT INTO ClientesDetalles(CAMPO1, CAMPO2, CAMPOX, CLIENTEID) VALUES ('BLA BLA', 'MAS', 'Y MAS BLA BLA', @idClientNew)
Esto es lo que tienes que hacer, así lo hago yo y ningún problema.

Un Saludo.



La franja horaria es GMT +2. Ahora son las 05:54:26.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi