I have a user table, basically:
CREATE TABLE IF NOT EXISTS 'sistema'.'user' (
'id_user' INT NOT NULL AUTO_INCREMENT COMMENT '',
'hashed_id' VARCHAR(40) NOT NULL COMMENT '',
'nome' VARCHAR(40) NOT NULL COMMENT '',
'cpf' VARCHAR(15) NOT NULL COMMENT '',
UNIQUE INDEX 'hashed_id_UNIQUE' ('hashed_id' ASC) COMMENT '',
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I want to create a trigger
for when a new user is created, hashed_id
is updated with a code of 12 numbers or letters, and I still have to make sure that hash
is unique, as long as it is not, generate other.
It would be something like this:
CREATE DEFINER = CURRENT_USER TRIGGER 'sistema'.'teste_BEFORE_INSERT' BEFORE
INSERT
ON
'teste' FOR EACH ROW
BEGIN
SELECT
@lid := LAST_INSERT_ID();
UPDATE
'sistema'.'teste'
SET
hashed_id = CONCAT(
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@lid) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(
@seed := ROUND(RAND(@seed) * 4294967296)
) * 36 + 1,
1
),
SUBSTRING(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
RAND(@seed) * 36 + 1,
1
)
)
WHERE
id = @lid;
END
This trigger
scheme is from here