Foros del Web » Programación para mayores de 30 ;) » Bases de Datos General » SQL Server »

Meter en una sentencia insert, el valor devuelto por un select

Estas en el tema de Meter en una sentencia insert, el valor devuelto por un select en el foro de SQL Server en Foros del Web. Quiero una sentencia que introduzca un dato, y después, coja esa id (con select @@identity) y la introduzca en otra tabla, pero todo dentro de ...
  #1 (permalink)  
Antiguo 29/09/2005, 14:59
 
Fecha de Ingreso: febrero-2005
Mensajes: 1.015
Antigüedad: 19 años, 2 meses
Puntos: 6
Meter en una sentencia insert, el valor devuelto por un select

Quiero una sentencia que introduzca un dato, y después, coja esa id (con select @@identity) y la introduzca en otra tabla, pero todo dentro de SQL (porque quiero hacer una transacción).

¿Cómo se haría? He probado con

INSERT... (normal)
INSERT INTO (campo1,...) values (select @@identity,...)

y variantes de esto y no me sale (supongo que se tendrá que declarar una variable y ponerle el valor del select, pero no sé cómo se hace).

Saludos

Nota: Estoy con SQL Server.
  #2 (permalink)  
Antiguo 29/09/2005, 15:37
Avatar de Mithrandir
Colaborador
 
Fecha de Ingreso: abril-2003
Mensajes: 12.106
Antigüedad: 21 años
Puntos: 25
@@identity es "inseguro", mejor usa SCOPE_IDENTITY().

Te sobra el SELECT entre los paréntesis:

INSERT... (normal)
INSERT INTO (campo1,...) values (SCOPE_IDENTITY() ,...)
__________________
"El hombre, en su orgullo, creó a Dios a su imagen y semejanza."
Friedrich Nietzsche
  #3 (permalink)  
Antiguo 29/09/2005, 19:07
 
Fecha de Ingreso: febrero-2005
Mensajes: 1.015
Antigüedad: 19 años, 2 meses
Puntos: 6
¡Muchas gracias!

Pero resulta que con esa id, no quiero hacer un insert sino muchos. ¿Cómo guardo el valor para ir usándolo en todos? (porque si pusiera @@identity en cada uno, o la función que tú me has dicho, me iría sacando la id pero del último insert hecho, no la del primero).

Pues de esta forma, que ya pregunté hace mucho tiempo y ya me respondiste:
http://www.forosdelweb.com/f21/usar-select-identity-manera-anidada-para-que-sirva-valor-otra-sentencia-330810/

Nota: ¿Por qué es inseguro @@identity?

Última edición por un_tio; 29/09/2005 a las 20:04
  #4 (permalink)  
Antiguo 30/09/2005, 14:06
Avatar de Mithrandir
Colaborador
 
Fecha de Ingreso: abril-2003
Mensajes: 12.106
Antigüedad: 21 años
Puntos: 25
Igual, simplemente lo almacenas en una variable temporal:

DECLARE @jeje INT
INSERT... (normal)
SET @jeje = SCOPE_IDENTITY()
INSERT INTO tabla (campo1,...) values ( @jeje,...)
INSERT INTO otratabla (campo1,...) values ( @jeje,...)
...

Sobre el porque es "inseguro", te cito lo que viene en la ayuda, en resumidas cuentas, el @@identity puede verse alterado por triggers o funciones corriendo por debajo:
Cita:
Iniciado por BOL
SCOPE_IDENTITY and @@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.

For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.

Assuming that both T1 and T2 have IDENTITY columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.

@@IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.

SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.
__________________
"El hombre, en su orgullo, creó a Dios a su imagen y semejanza."
Friedrich Nietzsche
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:39.