Update one column when another column of the same table is not null SQL Server

0

What happens is that I need to do something like:

IF Tabla1.GrupoId3 IS NOT NULL
UPDATE Tabla1 SET GrupoAnexado = 'x' WHERE MiCampo = 'Condiciones'
ELSE
UPDATE Tabla1 SET GrupoId3 = 'x' WHERE MiCampo = 'Condiciones'

But it marks me the following errors:

  

1) Invalid column name 'GroupId3'.

     

2) The multi-part identifier "Table1.GroupId3" could not be bound.

    
asked by ItzyV 14.09.2017 в 19:35
source

2 answers

0

If I understood your question correctly, it would be something like this:

UPDATE  Tabla1 
    SET GrupoAnexado = CASE WHEN GrupoId3 IS NULL THEN 'x' ELSE GrupoAnexado END,
        GrupoId3 = CASE WHEN GrupoId3 IS NOT NULL THEN 'x' ELSE GrupoId3 END
    WHERE MiCampo = 'Condiciones'

The condition to update each field will depend on GrupoId3 ( NULL or NOT NULL ), with the CASE we verify this and in one case we establish the value and in another we let it be the same field. The only issue that must be taken into account is: if you eventually have a trigger that verifies the UPDATE of some of these columns to do something, this would also be executed if you are updating it with the same value that you already have. If this were the case, to avoid it, there is no choice but to run the two sentences separately:

UPDATE  Tabla1 
    SET GrupoAnexado = 'X'
    WHERE MiCampo = 'Condiciones'
          AND GrupoId3 IS NULL

UPDATE  Tabla1 
    SET GrupoId3 = 'X'
    WHERE MiCampo = 'Condiciones'
          AND GrupoId3 IS NOT NULL
    
answered by 14.09.2017 / 20:17
source
0

It would only be done:

UPDATE Tabla1 
SET GrupoAnexado = 'x' 
WHERE 
    MiCampo = 'Condiciones' 
    AND GrupoId3 IS NOT NULL

Because the IF is already evaluated in WHERE .

    
answered by 14.09.2017 в 19:48