在纯 SQL 中,这将是最有效的,因为它会在匹配时立即停止搜索:
...作为存储过程:
CREATE PROCEDURE EmailExists
@email varchar(254) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @emailExists bit
SET @emailExists = 0
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Customer WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Member WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Instructor WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Employee WHERE email = @email)
END
END
END
SELECT @emailExists
END
...作为标量值函数:
CREATE FUNCTION EmailExists
(
@email varchar(254)
)
RETURNS bit
AS
BEGIN
DECLARE @emailExists bit
SET @emailExists = 0
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Customer WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Member WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Instructor WHERE email = @email)
IF @emailExists = 0
BEGIN
SELECT @emailExists = 1 WHERE EXISTS(SELECT 1 FROM Employee WHERE email = @email)
END
END
END
-- Return the result of the function
RETURN @emailExists
END
在带有 Linq 的 C# 中,您可以使用 Any 扩展名和 || 操作员。由于 Any 通常在 SQL 中被翻译为 EXISTS 并评估 || C# 中的运算符是惰性的,一旦到达电子邮件的第一次出现,评估就会停止。
bool emailExists = customerEmails.Any(e => string.Equals(e, email, StringComparison.InvariantCultureIgnoreCase))
|| memberEmails.Any(e => string.Equals(e, email, StringComparison.InvariantCultureIgnoreCase))
|| instructorEmails.Any(e => string.Equals(e, email, StringComparison.InvariantCultureIgnoreCase))
|| employeeEmails.Any(e => string.Equals(e, email, StringComparison.InvariantCultureIgnoreCase));