Prevent zero values in MySQL fields?

PHPz
Release: 2023-09-02 17:57:07
forward
1323 people have browsed it

防止 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)
Copy after login

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 ;
Copy after login

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
Copy after login

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)
Copy after login

Display all the records in the table using select statement-

mysql> select *from DemoTable;
Copy after login

This will produce the following output-

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!