Re: Insert into with IF condition
Date: August 27, 2011 08:42AM
> > if 1=1 (insert into acct_table(AcctSessionId) VALUES ('test') ELSE 'false' END;
Your parens are unbalanced, so it is unclear.
IF in an expression to be inserted:
INSERT INTO tbl (col) VALUES ( IF(condition, 'this', 'that') );
Another if/then/else type of expression:
CASE condition WHEN value THEN exp WHEN value THEN exp ELSE exp END
Try to insert, but silently do nothing if a UNIQUE or PRIMARY KEY id duplicated:
INSERT IGNORE INTO tbl ...;
Again, checking keys, but turning the INSERT into an UPDATE if there is a dup:
INSERT INTO tbl ... ON DUPLICATE KEY UPDATE ...;
Conditionally do a statement:
1. Declare a "stored procedure":
DELIMITER //
CREATE PROCEDURE proc(...)...
BEGIN;
IF (condition)
THEN
INSERT ...
ELSE
# no insert
END;
END //
DELIMITER ;
2. Use it:
CALL proc(...);
But the best way to conditionally execute a statement is to use Perl/PHP/Java/VB/etc to do that level of control flow.
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.