1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

MYSQL - How to use UPDATE with IF-ELSE condition

Discussion in 'MySQL' started by rahulephp, Oct 15, 2010.

  1. #1
    I have three columns - id, programname, status

    I wanted to use UPDATE with IF condition something like this:


    
    UPDATE elec_products
    	IF(programname ='Argos')	
    	(
    	    SET status = 1   
    	)
    	ELSEIF(programname ='sify')
    	(
    	    SET status = 2  
    	)
    	ELSE
    	(
    	    SET status = 3  
    	)
    	ENDIF
    WHERE programname IS NOT NULL
    
    Code (markup):

    I am not sure if it'll be possible. Please suggest the best possible ways to do this.
    Thank you
     
    rahulephp, Oct 15, 2010 IP
  2. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Try following.

    
    UPDATE elec_products
    SET STATUS = CASE
    WHEN programname = 'Argos' THEN
    	1
    WHEN programname = 'sify' THEN
    	2
    ELSE
    	3
    END
    WHERE programname IS NOT NULL;
    
    Code (markup):
     
    mastermunj, Oct 15, 2010 IP
  3. rahulephp

    rahulephp Peon

    Messages:
    45
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thats great. Thanks a lot.

    I just made a small change in query:

    UPDATE elec_products SET stats = CASE programmename WHEN 'Argos' THEN 1 WHEN 'stify' THEN 2 ELSE 3 END CASE WHERE programmename IS NOT NULL


    Thanks anyway
     
    rahulephp, Oct 15, 2010 IP
  4. abhineptune

    abhineptune Active Member

    Messages:
    178
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #4
    in a simple way to say take this as an example and try
    # UPDATE
    # [account]
    # SET
    # balance =
    # (
    # CASE
    # WHEN
    # ((balance - 10.00) < 0)
    # THEN
    # 0
    # ELSE
    # (balance - 10.00)
    # END
    # )
    # WHERE
    # id = 1


    and thanks
     
    abhineptune, Oct 15, 2010 IP
  5. rahulephp

    rahulephp Peon

    Messages:
    45
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Great and Thank you.
     
    rahulephp, Oct 15, 2010 IP
  6. flight05

    flight05 Active Member

    Messages:
    122
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #6
    Do it with php mate.
     
    flight05, Oct 22, 2010 IP