php - MySQL ON DUPLICATE KEY insert into an audit or log table -
is there way accomplish this?
insert ignore some_table (one,two,three) values(1,2,3) on duplicate key (insert audit_table values(now(),'duplicate key ignored')
i don't want use php :(
thanks!
if want consider using stored procedure, can use declare continue handler
. here's example:
create table users ( username varchar(30), first_name varchar(30), last_name varchar(30), primary key (username) ); create table audit_table (timestamp datetime, description varchar(255)); delimiter $$ create procedure add_user (in_username varchar(30), in_first_name varchar(30), in_last_name varchar(30)) modifies sql data begin declare duplicate_key int default 0; begin declare exit handler 1062 set duplicate_key = 1; insert users (username, first_name, last_name) values (in_username, in_first_name, in_last_name); end; if duplicate_key = 1 insert audit_table values(now(), 'duplicate key ignored'); end if; end$$ delimiter ;
let's add data, trying insert duplicate key:
call add_user('usera', 'bob', 'smith'); call add_user('userb', 'paul', 'green'); call add_user('usera', 'jack', 'brown');
result:
select * users; +----------+------------+-----------+ | username | first_name | last_name | +----------+------------+-----------+ | usera | bob | smith | | userb | paul | green | +----------+------------+-----------+ 2 rows in set (0.00 sec) select * audit_table; +---------------------+-----------------------+ | timestamp | description | +---------------------+-----------------------+ | 2010-10-07 20:17:35 | duplicate key ignored | +---------------------+-----------------------+ 1 row in set (0.00 sec)
if auditing important on database level, may want grant execute
permissions database users can call stored procedures.
Comments
Post a Comment