我在SO上看过一些相关的帖子,但是还没弄清楚这里发生了什么。我在Visual Studio 2013中有一个数据库项目。以下是一些简单的“用户”表的代码:
CREATE TABLE [dbo].[Users]
(
[ID] BIGINT IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Email] NVARCHAR(256) NOT NULL,
[Password] BINARY(20) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [IX_Users_Email] UNIQUE ([Email]),
CONSTRAINT [CK_Users] CHECK ([dbo].[CheckUserIsValid]([Users].[Name], [Users].[Email]) = 1)
)
以下是CheckUserIsValid的代码:
CREATE FUNCTION [dbo].[CheckUserIsValid]
(
@name NVARCHAR(50),
@email NVARCHAR(256)
)
RETURNS BIT
WITH SCHEMABINDING
AS
BEGIN
IF @name = ''
OR @email = ''
OR EXISTS(SELECT 1
FROM [dbo].[BlockedEmails]
WHERE [dbo].[BlockedEmails].[Email] = @email)
OR EXISTS(SELECT 1
FROM [dbo].[ApprovalCodes]
WHERE [dbo].[ApprovalCodes].[Email] = @email)
RETURN 0
RETURN 1
END
现在,奇怪的是,当我在构建项目之前打开代码文件时,VS不会显示任何错误。当我尝试构建它时,构建失败并且我得到了几个不同的错误:
我读过这可能与我在检查约束中使用标量函数的方式有关。现在相当困难。不知道下一步该尝试什么。
更新
因此,如果我保持函数不变,但将表更改为:
CREATE TABLE [dbo].[Users]
(
[ID] BIGINT IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Email] NVARCHAR(256) NOT NULL,
[Password] BINARY(20) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [IX_Users_Email] UNIQUE ([Email])
)
GO
ALTER TABLE [dbo].[Users] ADD CONSTRAINT [CK_Users] CHECK ([dbo].[CheckUserIsValid]([Users].[Name], [Users].[Email]) = 1)
GO
然后奇怪的是,它建立得很好。到底是什么?