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

utilizar campo autonumérico

Estas en el tema de utilizar campo autonumérico en el foro de SQL Server en Foros del Web. Buenas: Tengo dos campos: idnum (autonumérico/identity) y enlacefoto (varchar). La cuestión es que necesito obtener el valor identity justamente en la inserción para utilizarlo en ...
  #1 (permalink)  
Antiguo 10/04/2007, 10:25
Avatar de mruiz  
Fecha de Ingreso: septiembre-2001
Ubicación: Reykjavík
Mensajes: 138
Antigüedad: 22 años, 8 meses
Puntos: 0
utilizar campo autonumérico

Buenas:

Tengo dos campos: idnum (autonumérico/identity) y enlacefoto (varchar).
La cuestión es que necesito obtener el valor identity justamente en la inserción para utilizarlo en algunos casos para incluirlo como parte del campo enlacefoto, pero sólo en algunos casos.

¿Sabéis cómo hacerlo?

Gracias.
__________________
Mario Ruiz
http://tcberglind.blogspot.com
  #2 (permalink)  
Antiguo 11/04/2007, 09:11
 
Fecha de Ingreso: junio-2006
Mensajes: 109
Antigüedad: 17 años, 10 meses
Puntos: 2
Re: utilizar campo autonumérico

Utiliza la variable @@identity

Suerte
  #3 (permalink)  
Antiguo 12/04/2007, 13:17
Avatar de Mithrandir
Colaborador
 
Fecha de Ingreso: abril-2003
Mensajes: 12.106
Antigüedad: 21 años
Puntos: 25
Re: utilizar campo autonumérico

Usar @@identity tiene sus "asegunes". Dependiendo de que sea lo que necesites tienes que usar @@identity o Scope_Identity().

Documentate al respecto en la ayuda y si queda algo por discutir acá te ayudaremos.
__________________
"El hombre, en su orgullo, creó a Dios a su imagen y semejanza."
Friedrich Nietzsche
  #4 (permalink)  
Antiguo 12/04/2007, 14:42
Avatar de mruiz  
Fecha de Ingreso: septiembre-2001
Ubicación: Reykjavík
Mensajes: 138
Antigüedad: 22 años, 8 meses
Puntos: 0
Re: utilizar campo autonumérico

Gracias por vuestra ayuda.

No me queda muy claro qué pasaría si hay dos inserciones y de por medio pido el identity ¿cuál me daría? ¿cómo sé a cual se refiere?

Gracias.
__________________
Mario Ruiz
http://tcberglind.blogspot.com
  #5 (permalink)  
Antiguo 13/04/2007, 13:31
 
Fecha de Ingreso: junio-2006
Mensajes: 109
Antigüedad: 17 años, 10 meses
Puntos: 2
Re: utilizar campo autonumérico

En la ayuda de SQL te dan un ejemplo:

Código:
SCOPE_IDENTITY
Returns the last IDENTITY value inserted into an IDENTITY column in the same scope. A scope is a module -- a stored procedure, trigger, function, or batch. Thus, two statements are in the same scope if they are in the same stored procedure, function, or batch.

Syntax
SCOPE_IDENTITY( )

Return Types
sql_variant

Remarks
SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in that they return values inserted into IDENTITY columns. 

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.

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.

See Examples for an illustration.

Examples
This example creates two tables, TZ and TY, and an INSERT trigger on TZ. When a row is inserted to table TZ, the trigger (Ztrig) fires and inserts a row in TY.

USE tempdb
GO
CREATE TABLE TZ (
   Z_id  int IDENTITY(1,1)PRIMARY KEY,
   Z_name varchar(20) NOT NULL)

INSERT TZ
   VALUES ('Lisa')
INSERT TZ
   VALUES ('Mike')
INSERT TZ
   VALUES ('Carla')

SELECT * FROM TZ

--Result set: This is how table TZ looks
Z_id   Z_name
-------------
1      Lisa
2      Mike
3      Carla

CREATE TABLE TY (
   Y_id  int IDENTITY(100,5)PRIMARY KEY,
   Y_name varchar(20) NULL)

INSERT TY (Y_name)
   VALUES ('boathouse')
INSERT TY (Y_name)
   VALUES ('rocks')
INSERT TY (Y_name)
   VALUES ('elevator')

SELECT * FROM TY
--Result set: This is how TY looks:
Y_id  Y_name
---------------
100   boathouse
105   rocks
110   elevator

/*Create the trigger that inserts a row in table TY 
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS 
   BEGIN
   INSERT TY VALUES ('')
   END

/*FIRE the trigger and find out what identity values you get 
with the @@IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT   @@IDENTITY AS [@@IDENTITY]
GO

--Here is the result set.
SCOPE_IDENTITY
4
/*SCOPE_IDENTITY returned the last identity value in the same scope, which was the insert on table TZ*/

@@IDENTITY
115
/*@@IDENTITY returned the last identity value inserted to TY by the trigger, which fired due to an earlier insert on TZ*/
  #6 (permalink)  
Antiguo 14/04/2007, 08:43
Avatar de mruiz  
Fecha de Ingreso: septiembre-2001
Ubicación: Reykjavík
Mensajes: 138
Antigüedad: 22 años, 8 meses
Puntos: 0
Re: utilizar campo autonumérico

Si lo he entendido bien entonces lo que debo de utilizar justamente después de hacer el insert es SCOPE_IDENTITY y de esta forma obtendré el identity de la fila que acabo de insertar.

Muchísimas gracias a todos.
Esperaré un par de días y daré por cerrada la conversación como solucionada.
__________________
Mario Ruiz
http://tcberglind.blogspot.com
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 12:06.