Home  >  Article  >  Database  >  Prevent zero values ​​in MySQL fields?

Prevent zero values ​​in MySQL fields?

PHPz
PHPzforward
2023-09-02 17:57:071355browse

防止 MySQL 字段出现零值?

Use the BEFORE INSERT trigger on the table to prevent zero values ​​from appearing in MySQL fields. Let us first create a table -

mysql> create table DemoTable(Value int);
Query OK, 0 rows affected (0.85 sec)

Let us create a trigger to prevent zero values ​​from appearing in a MySQL field -

mysql> DELIMITER //
mysql> create trigger preventing_to_insert_zero_value
   before insert on DemoTable
   for each row
   begin
      if(new.Value = 0) then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'You can not provide 0 value';
   END if;
end
//
Query OK, 0 rows affected (0.34 sec)
mysql> DELIMITER ;

Let us insert a 0 value in the table and check if the value will is inserted. It will not allow -

mysql> insert into DemoTable values(0);
ERROR 1644 (45000): You cannot provide 0 value

So, in the above table, 0 values ​​cannot be inserted due to triggers. However, you can insert some other values.

Now let us insert some records in the table using insert command-

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(-1000);
Query OK, 1 row affected (0.41 sec)

Display all the records in the table using select statement-

mysql> select *from DemoTable;

This will produce the following output-

+-------+
| Value |
+-------+
| 10    |
| -1000 |
+-------+
2 rows in set (0.00 sec)

The above is the detailed content of Prevent zero values ​​in MySQL fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete