我是sql编程的新手。这是我的数据库类的家庭作业。我已经完成了作业所需的所有表格,我只是挂了一部分。作业中的内容如下:
如果type为'faculty',则电子邮件地址必须以'@ xxx.edu'
结尾
这就是表格的样子:
create table customer
(
CID# char(10) primary key IDENTITY (1,1) NOT NULL,
F_name varchar(20),
M_name varchar(20),
L_name varchar(20),
type varchar(20),
street varchar(20),
city varchar(20),
state varchar(20),
zip char(5),
password varchar (20) NOT NULL,
email varchar(20) NOT NULL
Constraint CK_customer_type check (type in ('student', 'faculty'))
)
任何有人可以借出的帮助都将不胜感激!
答案 0 :(得分:1)
此约束将检查电子邮件列是否以@xxx.edu
结尾。
Constraint CK_email_faculty check (
type<>'faculty' OR
CHARINDEX('@xxx.edu',email)=LEN(email)-LEN('@xxx.edu')+1
)
备注1:比在CHECK约束中检查适当的类型更好,制作一个包含可能类型的表customer_type
('student','faculty'...),并在{{中有一个外键1}}指向一个类型。
customer
在CREATE TABLE customer_type(id INT NOT NULL PRIMARY KEY,desc VARCHAR(128));
INSERT INTO customer_type(id,desc)VALUES(1,'student');
INSERT INTO customer_type(id,desc)VALUES(2,'faculty');
表中有一个外键指向customer
表:
customer_type
然后您不会插入类型描述,而是插入类型标识符:
CREATE TABLE customer(
-- ...
type INT NOT NULL,
-- ...
CONSTRAINT FK_type_customer_type FOREIGN KEY(type) REFERENCES customer_type(id)
)
这样可以节省SQL Server缓存这些表时的磁盘空间和内存。
备注2:varchar字段的宽度非常小。电子邮件地址只有20个字符?
答案 1 :(得分:1)
对于您的特定情况,这样的约束可能没问题:
Constraint CK_customer_email check (
type <> 'faculty' OR
email LIKE '%_%@_%.edu'
CHARINDEX('@xxx.edu',email)=LEN(email)-LEN('@xxx.edu')+1
)
这将允许1个以上的字符,然后是@,后跟1个字符,然后是.edu
。
然而,在现实生活中(意味着人们试图插入错误的电子邮件地址),validation is more complex(并非所有字符都被允许),因此可以使用自定义功能。一个似乎几乎完整的提供here:
CREATE FUNCTION [dbo].[fnAppEmailCheck](@email VARCHAR(255))
--Returns true if the string is a valid email address.
RETURNS bit
as
BEGIN
DECLARE @valid bit
IF @email IS NOT NULL
SET @email = LOWER(@email)
SET @valid = 0
IF @email like '[a-z,0-9,_,-]%@[a-z,0-9,_,-]%.[a-z][a-z]%'
AND LEN(@email) = LEN(dbo.fnAppStripNonEmail(@email))
AND @email NOT like '%@%@%'
AND CHARINDEX('.@',@email) = 0
AND CHARINDEX('..',@email) = 0
AND CHARINDEX(',',@email) = 0
AND RIGHT(@email,1) between 'a' AND 'z'
SET @valid=1
RETURN @valid
END
然后,您的约束将是这样的:
Constraint CK_customer_email check (
type <> 'faculty' OR
[dbo].[fnAppEmailCheck] (email) = 1
)
答案 2 :(得分:0)
添加约束
Constraint CK_email check (email like case when type in ('faculty') then '%@xxx.edu' else email end )