Reputation: 3068
As a database designer ,I need to create a trigger at the table so that I can create the new value at the column PIB_DTL_CD
as PIB0000000001
when the
value at the column PIB_DTL_ID
is 1
(auto increment, private key)
I need to create the trigger but I am not where the error is about . Would you please tell me what is the recommend practice ?
I would like to create a mysql trigger to
Here is my SQL Code for the trigger:
CREATE TRIGGER `b_pib_ref_gen`
BEFORE INSERT ON `prd_test6`.`b_pib_detail` FOR EACH ROW
BEGIN
IF new.PIB_DTL_CD IS NULL
set @auto_id := (SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='b_pib_detail' AND TABLE_SCHEMA=DATABASE() );
set NEW.PIB_DTL_CD = CONCAT('PIB', LPAD( @auto_id + 1 , 10, '0')) ;
ENF IF;
END;
Updates:
Maria DB Version is 10.4.8-MariaDB
Upvotes: 0
Views: 40
Reputation: 17665
Have you thought of using generated columns?
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 22
Server version: 10.1.14-MariaDB mariadb.org binary distribution
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [sandbox]> drop table if exists t;
Query OK, 0 rows affected (0.10 sec)
MariaDB [sandbox]> create table t
-> (id int auto_increment primary key, val int,
-> pb_id varchar(20) as (concat('pb',LPAD(id, 10, '0')))
-> );
Query OK, 0 rows affected (0.22 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> insert into t(val) values
-> (1),(2);
Query OK, 2 rows affected (0.05 sec)
Records: 2 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+----+------+--------------+
| id | val | pb_id |
+----+------+--------------+
| 1 | 1 | pb0000000001 |
| 2 | 2 | pb0000000002 |
+----+------+--------------+
2 rows in set (0.00 sec)
Upvotes: 1