在数据库中的电子邮件列上强制执行数据完整性

Upw*_*rdD 7 sql-server t-sql

我想对电子邮件列进行限制,如下所示:xxxx@xxxx.yyy 显然“x”具有各种长度,x 是一些字符串数据,而 .yyy 是 .com、.gov 等的域类型

Wor*_*DBA 6

如果你想正确地完成它,这是一项太大的任务。如果您能够使用 SQL CLR,尽管我们公司是这样做的:

using System;
using System.Net.Mail;
using Microsoft.SqlServer.Server;

namespace Functions
{
    public static class Utilities
    {
        [SqlFunction]
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrEmpy(email))
                return false;

            bool isValid = false;
            try
            {
                // use the validation provided by the System.Net.Mail.MailAddress class            
                var mailAddress = new MailAdress(email); 
                isValid = true;
            }
            catch(FormatException)
            {
                isValid = false;
            }
            return isValid;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后假设您部署它,因为dbo.fn_IsValidEmail您可以在检查约束中使用它,就像使用任何其他标量函数一样:

create table dbo.tbl
(
    id int identity not null,
    email nvarchar(256) not null,
    constraint ck_tbl_isValidEmail check (dbo.fn_IsValidEmail (email))
);
Run Code Online (Sandbox Code Playgroud)

如果您的列允许,NULL那么您需要将函数的第一部分改为:

if (email == null)
    return true;
if (email == string.Empty)
    return false;
Run Code Online (Sandbox Code Playgroud)

文档:

System.Net.Mail.MailAddress

Microsoft.SqlServer.Server.SqlFunctionAttribute

CLR 函数