Actualizar varias columnas en SQL


¿Hay una manera de actualizar varias columnas en SQL server de la misma manera que se usa una instrucción insert?

Algo como:

Update table1 set (a,b,c,d,e,f,g,h,i,j,k)=
(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k)
from table2 t2
where table1.id=table2.id

O algo así, en lugar de así:

update table set a=t2.a,b=t2.b etc 

Que puede ser bastante tedioso escribir si tiene más de 100 columnas.

Author: Tim Lehner, 2012-01-31

12 answers

La "forma aburrida" es SQL estándar y cómo lo hacen los RDBMS convencionales.

Con más de 100 columnas, es muy probable que tenga un problema de diseño... además, hay métodos de mitigación en las herramientas del cliente (por ejemplo, declaraciones de ACTUALIZACIÓN de generación) o mediante el uso deMs

 71
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 12:39:51

Prueba esto:

UPDATE table1 
SET a = t2.a, b = t2.b, .......
FROM table2 t2
WHERE table1.id = t2.id

Eso debería funcionar en la mayoría de los dialectos SQL, excluyendo Oracle.

Y sí, es mucho escribir, es la forma en que SQL hace esto.

 158
Author: marc_s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-29 11:05:25

La sintaxis Update table1 set (a,b,c) = (select x,y,x) es un ejemplo del uso de constructores de valores de fila, Oracle soporta esto, MSSQL no lo hace. (Conectar elemento)

 20
Author: Alex K.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 12:58:16

Su consulta es casi correcta. El T-SQL para esto es:

UPDATE  Table1
SET     Field1 = Table2.Field1,
        Field2 = Table2.Field2,
        other columns...
FROM    Table2
WHERE   Table1.ID = Table2.ID
 15
Author: John Woo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 12:42:05
   UPDATE t1 
    SET 
    t1.a = t2.a,
    t1.b = t2.b,
    .
    .
    .


    FROM 
    table1 t1 
    INNER JOIN table2 t2 ON  t1.id=t2.id

Puedes probar esto

 8
Author: Thangamani Palanisamy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-28 10:36:04

Sintaxis

UPDATE table-name 
SET column-name = value, column-name = value, ...
WHERE condition

Ejemplo

UPDATE school
SET course = 'mysqli', teacher = 'Tanzania', student = 'you'
WHERE id = 6
 8
Author: betrice mpalanzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 06:54:29

Aquí hay uno que funciona:

UPDATE  `table_1`
INNER JOIN 
 `table_2` SET  col1= value, col2= val,col3= val,col4= val;

El valor es la columna de table_2

 1
Author: Dragos Custura,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-17 20:40:07

Si necesita volver a escribir esto varias veces, puede hacer lo que hice una vez. Obtenga los nombres de sus columnas en filas en la hoja de excel (escriba al final del nombre de cada columna ( = ), que es fácil en notepad++) en el lado derecho haga una columna para copiar y pegar su valor que corresponderá a las nuevas entradas en cada columna. A continuación, a la derecha de ellos en una columna independiente poner las comas como diseñado

Entonces tendrá que copiar sus valores en la columna central cada vez y luego pegarlos entonces y ejecutar

No conozco una solución más fácil

 0
Author: Mohamed Bekheit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-15 06:49:34

He intentado con esta manera y su funcionamiento bien :

UPDATE 
  Sub2 
SET 
  SLNNOND = Sub.SLNNOND, 
  Sub2.SLNNONF = Sub.SLNNONF 
FROM 
  #TEMP Sub2
 0
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 19:42:38

Hice esto en MySQL y actualizó varias columnas en un solo registro, así que intente esto si está utilizando MySQL como su servidor:

"UPDATE creditor_tb SET credit_amount='" & CDbl(cur_amount) & "'
                   , totalamount_to_pay='" & current_total & "',   
        WHERE credit_id='" & lbcreditId.Text & "'". 

Sin embargo, estaba codificando en vb.net usando MySQL server, pero puede llevarlo a su lenguaje de programación favorito en la medida en que esté utilizando MySQL como su servidor.

 -3
Author: Michael Kisingi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-25 12:48:52
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

Http://www.w3schools.com/sql/sql_update.asp

 -4
Author: Mellad Qarizada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-13 03:51:48
update T1
set T1.COST2=T1.TOT_COST+2.000,
T1.COST3=T1.TOT_COST+2.000,
T1.COST4=T1.TOT_COST+2.000,
T1.COST5=T1.TOT_COST+2.000,
T1.COST6=T1.TOT_COST+2.000,
T1.COST7=T1.TOT_COST+2.000,
T1.COST8=T1.TOT_COST+2.000,
T1.COST9=T1.TOT_COST+2.000,
T1.COST10=T1.TOT_COST+2.000,
T1.COST11=T1.TOT_COST+2.000,
T1.COST12=T1.TOT_COST+2.000,
T1.COST13=T1.TOT_COST+2.000
from DBRMAST T1 
inner join DBRMAST t2 on t2.CODE=T1.CODE
 -7
Author: oracle passion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-10 13:00:13