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

Sentencia update con if

Estas en el tema de Sentencia update con if en el foro de SQL Server en Foros del Web. Buenas tardes, necesito introducir un if dentro de una sentencias update en SQL Server 2008. Ahora mismo lo tengo de esta forma: UPDATE DIRINFO SET ...
  #1 (permalink)  
Antiguo 18/04/2012, 08:11
 
Fecha de Ingreso: julio-2010
Mensajes: 93
Antigüedad: 13 años, 9 meses
Puntos: 0
Sentencia update con if

Buenas tardes,

necesito introducir un if dentro de una sentencias update en SQL Server 2008. Ahora mismo lo tengo de esta forma:

UPDATE DIRINFO
SET Archivo = DRF.Archivo, Tipo = DRF.Tipo,
Operador = O.Uid, Fecha_permanencia = IF(OPERADOR = O.UID, Fecha_permanencia, DRF.FECHA), Especial = DRF.Especial
FROM DIRINFO DF
INNER JOIN DRF
ON DF.Telefono = DRF.Telefono
INNER JOIN OPERADOR O
ON DRF.Operador = O.CMT
WHERE DF.Telefono = DRF.Telefono


Pero me genera un error y les agradecería si me pudiesen ayudar a solucionarlo.

Un saludo.
  #2 (permalink)  
Antiguo 18/04/2012, 08:28
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Sentencia update con if

Puedes hacerlo algo asi:

Código SQL:
Ver original
  1. UPDATE TABLE
  2. SET TABLE.VALUE=t1.VALUE
  3. FROM
  4. (
  5. SELECT CASE WHEN operador=1 THEN fecha1 ELSE fecha2 AS fecha, datos FROM
  6. IRINFO DF
  7. INNER JOIN DRF
  8. ON DF.Telefono = DRF.Telefono
  9. INNER JOIN OPERADOR O
  10. ON DRF.Operador = O.CMT
  11. WHERE DF.Telefono = DRF.Telefono
  12. ) AS t1

Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #3 (permalink)  
Antiguo 18/04/2012, 08:36
 
Fecha de Ingreso: julio-2010
Mensajes: 93
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: Sentencia update con if

No entiendo muy bien la manera en que lo haces, si me puedes orientar un poco te lo agradecería.

Un saludo.
  #4 (permalink)  
Antiguo 18/04/2012, 09:03
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Sentencia update con if

metes la consulta de donde sacas los valores en un subquery en el ejemplo t1 y dentro de este subquery puedes poner un case para lo que necesitas:
Para que se entienda mejor
Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. nombre VARCHAR(10),
  4. date1 datetime,
  5. date2 datetime,
  6. STATUS bit
  7. )
  8.  
  9. INSERT INTO #temp VALUES ('libras',getdate(),getdate()-1,1)
  10. INSERT INTO #temp VALUES ('libras1',getdate(),getdate()-2,0)
  11. INSERT INTO #temp VALUES ('libras2',getdate(),getdate()-3,0)
  12. INSERT INTO #temp VALUES ('libras3',getdate(),getdate()-4,1)
  13. INSERT INTO #temp VALUES ('libras4',getdate(),getdate()-5,1)
  14.  
  15.  
  16. SELECT * FROM #temp
  17.  
  18. nombre  date1   date2   STATUS
  19. libras  2012-04-18 10:59:01.860 2012-04-17 10:59:01.860 1
  20. libras1 2012-04-18 10:59:01.860 2012-04-16 10:59:01.860 0
  21. libras2 2012-04-18 10:59:01.860 2012-04-15 10:59:01.860 0
  22. libras3 2012-04-18 10:59:01.860 2012-04-14 10:59:01.860 1
  23. libras4 2012-04-18 10:59:01.860 2012-04-13 10:59:01.860 1
  24.  
  25.  
  26. UPDATE #temp
  27. SET date1=t1.fecha
  28. FROM
  29. (
  30. SELECT CASE WHEN STATUS=1 THEN date2 ELSE date1 END AS fecha,nombre,STATUS FROM #temp
  31. ) AS t1 WHERE t1.nombre=#temp.nombre
  32.  
  33. SELECT * FROM #temp
  34.  
  35. nombre  date1   date2   STATUS
  36. libras  2012-04-17 10:59:01.860 2012-04-17 10:59:01.860 1
  37. libras1 2012-04-18 10:59:01.860 2012-04-16 10:59:01.860 0
  38. libras2 2012-04-18 10:59:01.860 2012-04-15 10:59:01.860 0
  39. libras3 2012-04-14 10:59:01.860 2012-04-14 10:59:01.860 1
  40. libras4 2012-04-13 10:59:01.860 2012-04-13 10:59:01.860 1

Si te fijas nada cambio la fecha date1 por la fecha date2 solo en los campos en donde status=1 que es mas o menos lo que necesitas no??

Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #5 (permalink)  
Antiguo 18/04/2012, 09:19
 
Fecha de Ingreso: julio-2010
Mensajes: 93
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: Sentencia update con if

Te entiendo, el problema es que yo no solo quiero hacerle un update a un campo de mi tabla, sino a varios a la vez.

Como tu lo haces solo actualiza la fecha, que es lo que necesito, pero también quiero que me actualice el resto de campos, como muestro en el promer post.

Un saludo.
  #6 (permalink)  
Antiguo 18/04/2012, 09:26
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Sentencia update con if

¬¬ pues nada mas agregas estos campos que quieres actualizar a tu select algo asi:

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. id INT IDENTITY(1,1),
  4. nombre VARCHAR(10),
  5. date1 datetime,
  6. date2 datetime,
  7. STATUS bit
  8. )
  9.  
  10. INSERT INTO #temp VALUES ('libras',getdate(),getdate()-1,1)
  11. INSERT INTO #temp VALUES ('libras1',getdate(),getdate()-2,0)
  12. INSERT INTO #temp VALUES ('libras2',getdate(),getdate()-3,0)
  13. INSERT INTO #temp VALUES ('libras3',getdate(),getdate()-4,1)
  14. INSERT INTO #temp VALUES ('libras4',getdate(),getdate()-5,1)
  15.  
  16.  
  17. SELECT * FROM #temp
  18.  
  19. id  nombre  date1   date2   STATUS
  20. 1   libras  2012-04-18 11:22:18.853 2012-04-17 11:22:18.853 1
  21. 2   libras1 2012-04-18 11:22:18.853 2012-04-16 11:22:18.853 0
  22. 3   libras2 2012-04-18 11:22:18.853 2012-04-15 11:22:18.853 0
  23. 4   libras3 2012-04-18 11:22:18.853 2012-04-14 11:22:18.853 1
  24. 5   libras4 2012-04-18 11:22:18.853 2012-04-13 11:22:18.853 1
  25.  
  26. UPDATE #temp
  27. SET date1=t1.fecha,
  28.     nombre=t1.nombre,
  29.     STATUS=t1.STATUS
  30. FROM
  31. (
  32. SELECT id,CASE WHEN STATUS=1 THEN date2 ELSE date1 END AS fecha,'sin nombre' AS nombre,
  33. CASE WHEN STATUS=1 THEN 0 ELSE 1 END AS STATUS FROM #temp
  34. ) AS t1 WHERE t1.id=#temp.id
  35.  
  36. SELECT * FROM #temp
  37.  
  38. id  nombre  date1   date2   STATUS
  39. 1   sin nombre  2012-04-17 11:22:18.853 2012-04-17 11:22:18.853 0
  40. 2   sin nombre  2012-04-18 11:22:18.853 2012-04-16 11:22:18.853 1
  41. 3   sin nombre  2012-04-18 11:22:18.853 2012-04-15 11:22:18.853 1
  42. 4   sin nombre  2012-04-14 11:22:18.853 2012-04-14 11:22:18.853 0
  43. 5   sin nombre  2012-04-13 11:22:18.853 2012-04-13 11:22:18.853 0

El mismo query actualizando "muchos" datos
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #7 (permalink)  
Antiguo 18/04/2012, 09:45
 
Fecha de Ingreso: julio-2010
Mensajes: 93
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: Sentencia update con if

Lo he dejado de la siguiente manera y me tira un error en lo marcado en rojo:

UPDATE DIRINFO
SET Archivo = T1.Archivo,
Tipo = T1.Tipo,
Operador = T1.OPERADOR,
Fecha_registro = T1.FECHA,
Fecha_permanencia = T1.FECHAPERM,
Especial = T1.ESPECIAL
FROM
(
SELECT CASE WHEN DF.Operador = O.Uid THEN DF.Fecha_permanencia ELSE DRF.FECHA AS FECHAPERM, DRF.Archivo AS ARCHIVO, DRF.Tipo AS TIPO,
O.Uid AS OPERADOR, DRF.Fecha AS FECHA, DRF.Especial AS ESPECIAL
FROM DIRINFO DF
INNER JOIN DRF
ON DF.Telefono = DRF.Telefono
INNER JOIN OPERADOR O
ON DRF.Operador = O.CMT
WHERE DF.Telefono = DRF.Telefono
) AS T1
  #8 (permalink)  
Antiguo 18/04/2012, 09:56
 
Fecha de Ingreso: julio-2010
Mensajes: 93
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: Sentencia update con if

Error mío, me faltaba el "END" del final de la sentencia CASE. Ahora ya no me genera errores y funciona perfecto.

Muchas gracias.

Un saludo.
  #9 (permalink)  
Antiguo 18/04/2012, 10:09
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Sentencia update con if

que bien que funciono :)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me

Etiquetas: fecha, sentencia, server, sql, update
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

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 03:58.