2

I have a table with a slug field. It's possible to populate automatically this field with a function by manipulation of another field?

Something like:

INSERT INTO people('name','slug') VALUES ('xxxx',SLUG(name));
WalterV
  • 1,490
  • 2
  • 21
  • 33

1 Answers1

6

Are you looking for something like this?

CREATE TABLE people
(`name` varchar(128), `slug` varchar(128));

-- It's not a real function it's just an oversimplified example
-- you need to implement your own logic     
CREATE FUNCTION NAME_SLUG(name VARCHAR(128))
RETURNS VARCHAR(128)
  RETURN LOWER(REPLACE(name, ' ', '-'));

CREATE TRIGGER tg_people_insert
BEFORE INSERT ON people
FOR EACH ROW
  SET NEW.slug = NAME_SLUG(NEW.name);

INSERT INTO people (`name`)
VALUES ('Jhon Doe'),('Ian Martin Louis'), ('Mark Lee');

SELECT * FROM people;

Output:

|             NAME |             SLUG |
---------------------------------------
|         Jhon Doe |         jhon-doe |
| Ian Martin Louis | ian-martin-louis |
|         Mark Lee |         mark-lee |

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157
  • 1
    @WalterVilla You're very welcome. I wasn't sure I got you right but I'm glad I could help :) – peterm Jul 25 '13 at 11:49