Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Conexión con bases de datos
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Conexión con bases de datos

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 14-12-2016
raul_toled raul_toled is offline
Registrado
 
Registrado: ene 2007
Posts: 9
Poder: 0
raul_toled Va por buen camino
Exclamation 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
Responder Con Cita
  #2  
Antiguo 14-12-2016
luisgutierrezb luisgutierrezb is offline
Miembro
 
Registrado: oct 2005
Ubicación: México
Posts: 925
Poder: 19
luisgutierrezb Va por buen camino
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.
Responder Con Cita
  #3  
Antiguo 15-12-2016
raul_toled raul_toled is offline
Registrado
 
Registrado: ene 2007
Posts: 9
Poder: 0
raul_toled Va por buen camino
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 Ver Mensaje
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.
Responder Con Cita
  #4  
Antiguo 15-12-2016
Avatar de olbeup
olbeup olbeup is offline
Miembro
 
Registrado: jul 2005
Ubicación: Santiago de la Ribera (España)
Posts: 685
Poder: 19
olbeup Va camino a la fama
Cita:
Empezado por raul_toled Ver Mensaje
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.
__________________
Al hacer una consulta SQL, haz que los demás te entiendan y disfruten de ella, será tú reflejo de tú saber.
Responder Con Cita
  #5  
Antiguo 15-12-2016
raul_toled raul_toled is offline
Registrado
 
Registrado: ene 2007
Posts: 9
Poder: 0
raul_toled Va por buen camino
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 Ver Mensaje
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.
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Clientdataset ..applyupdate rodrinig Firebird e Interbase 2 05-11-2013 21:35:42
Al llamar a ApplyUpdate(0) de un ClientDataSet la aplicación se cuelga lmhjob Conexión con bases de datos 8 03-09-2008 17:40:58
Estado ClientDataSet tras ApplyUpdate Rockin Conexión con bases de datos 1 18-07-2008 16:39:11
autonumerico con ClientDataSet Johnny Q Conexión con bases de datos 0 07-10-2005 20:13:53


La franja horaria es GMT +2. Ahora son las 19:23:21.


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
Copyright 1996-2007 Club Delphi