2

I have a table I'm trying to add a unique index to. Problem is, the way the script is set up that inserts data, there will be on occasion, some empty strings instead of NULL.

So, aside from changing the script (which I foresee being necessary unless someone saves me!).... is there any setting in mysql that can automatically use NULL value if an empty string is passed through to the unique key?

4

2 回答 2

5

If you can't fix the import script then you should be able to use a trigger to patch things up before INSERTs or UPDATEs get to the table. Something like this should do the trick:

delimiter $$
create trigger nullify_blanks_ins before insert on your_table
for each row begin
    if new.string = '' then
        set new.string = null;
    end if;
end;
$$
create trigger nullify_blanks_upd before update on your_table
for each row begin
    if new.string = '' then
        set new.string = null;
    end if;
end;
$$  
delimiter ;

new here refers to what the row will look like after the INSERT or UPDATE completes so you can look for the garbage values and fix them. Then, since these are BEFORE triggers, your patched rows will go into the database. You would, of course, have to change the table (your_table) and column (string) names to suit your situation.

于 2012-10-24T04:02:56.413 回答
0

try something like

SET sn=NULLIF(sn,NULL);

or

UPDATE Table
  SET demo = CASE demo = ' ' THEN NULL ELSE demo END,
  ...
于 2012-10-24T03:29:17.237 回答