如何编写查询以确保电子邮件包含 @ [英] How to write a query to ensure email contains @
问题描述
我正在 db2 中创建一个数据库,我想添加一个约束来验证用户是否插入了包含 %@%.% 的有效电子邮件地址.没有运气......有什么建议吗?
I'm creating a database in db2 and I want to add a constrain to validate whether the user inserting a valid email address, that contain %@%.% . Without luck...any advice?
推荐答案
您可以将 LIKE 与通配符一起使用.请参阅 这里 获取 DB2 上的通配符.
You can use LIKE with wildcards. See here for the wildcards on DB2.
下划线字符 (_) 代表任何单个字符.
The underscore character ( _ ) represents any single character.
百分号字符 (%) 表示零个或多个字符的字符串.
The percent sign character (%) represents a string of zero or more characters.
SELECT email
FROM YourTable
WHERE email NOT LIKE '%_@__%.__%'
这将忽略以下情况(有效电子邮件的简单版本):
This will ignore the following cases (simple version for valid emails):
- @前至少有一个字符的电子邮件;
- @ 和 . 之间至少有两个字符的电子邮件;
- 之间至少有两个字符的电子邮件.和结束.
您可以在 sqlfiddle 中查看 MySql 中的示例.
You can see an example in MySql in sqlfiddle.
要将其添加为约束,您可以这样做(正如 mustaccio 在评论中所说):
To add it as a constraint, you do (as mustaccio said in a comment):
alter table your_table add constraint chk_email check (email like '%_@__%.__%')
这篇关于如何编写查询以确保电子邮件包含 @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!