SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

前端 未结 6 629
花落未央
花落未央 2020-12-08 07:29

I have the following SQL query:

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = \'2\' AND row_nr = \'1\') 
   UPDATE component_psar
      SET col_1 = \         


        
相关标签:
6条回答
  • 2020-12-08 07:48

    Here is the link to documentation INSERT ... ON DUPLICATE Statement.

    0 讨论(0)
  • 2020-12-08 07:50

    You have to add THEN

    IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
    THEN
    UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
    ELSE 
    INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
    
    0 讨论(0)
  • 2020-12-08 07:55

    Isn't this maybe the most elegant?

    REPLACE 
    INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) 
    VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
    

    see: http://dev.mysql.com/doc/refman/5.7/en/replace.html

    0 讨论(0)
  • 2020-12-08 07:58
    INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
    VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
    ON DUPLICATE KEY UPDATE col_1 = VALUES(col_1), col_2 = VALUES(col_2), col_3 = VALUES(col_3), col_4 = VALUES(col_4), col_5 = VALUES(col_5), col_6 = VALUES(col_6), unit = VALUES(unit), add_info = VALUES(add_info), fsar_lock = VALUES(fsar_lock)
    

    Would work with tbl_id and row_nr having UNIQUE key.

    This is the method DocJonas linked to with an example.

    0 讨论(0)
  • 2020-12-08 08:11

    In this approach only one statement is executed when the UPDATE is successful.

    -- For each row in source
    BEGIN TRAN    
    
    UPDATE target
    SET <target_columns> = <source_values>
    WHERE <target_expression>
    
    IF (@@ROWCOUNT = 0)
       INSERT target (<target_columns>)
    VALUES (<source_values>)
    
    COMMIT
    
    0 讨论(0)
  • 2020-12-08 08:13

    Use the following Statement:

    IF EXISTS(SELECT * FROM prueba )
    then
      UPDATE prueba
      SET nombre = '1', apellido = '1' 
      WHERE cedula = 'ct'
    ELSE 
      INSERT INTO prueba (cedula, nombre, apellido)
      VALUES ('ct', 'ct', 'ct');
    
    0 讨论(0)
提交回复
热议问题