SQL Server约束增强的两点建议
发布时间:2024-01-28 04:43:10
在许多情况下,对外键使用更复杂的逻辑表达式是非常有用的。 此外,在某些情况下能够在索引视图创建约束也将非常实用。 我将举例说明,同时我希望针对此文的投票链接会尽快加上。
当外键中需要更为复杂的逻辑表达式时
考虑下面的简单常识: 您的设备的最大电流不能超过您插入到它的电路的最大电流。 假设下面的表存储电路和设备数据:
CREATE TABLE Data.Curcuits(CurcuitID INT NOT NULL
CONSTRAINT PK_Curcuits PRIMARY KEY,
MaximumCurrent INT NOT NULL,
Description VARCHAR(100) NOT NULL);
GO
INSERT INTO Data.Curcuits(CurcuitID,
MaximumCurrent,
Description)
SELECT 1, 25, 'Deck and Garage';
GO
CREATE TABLE Data.Devices(DeviceID INT NOT NULL
CONSTRAINT PK_Devices PRIMARY KEY,
CurcuitID INT NULL,
MaximumCurrent INT NOT NULL,
Description VARCHAR(100) NOT NULL,
CONSTRAINT FK_Devices_Curcuits FOREIGN KEY(CurcuitID)
REFERENCES Data.Curcuits(CurcuitID)
);
GO
It would be very convenient to issue a simple command and implement this business rule:
一个非常简便的命令就可能实现这个业务规则:
ALTER TABLE Data.Devices ADD CONSTRAINT FK_Devices_Curcuits
FOREIGN KEY(CurcuitID, MaximumCurrent)
REFERENCES Data.Curcuits(CurcuitID, MaximumCurrent)
MATCH ON((Data.Devices.CurcuitID = Data.Curcuits.CurcuitID) AND
(Data.Devices.MaximumCurrent <= Data.Curcuits.MaximumCurrent));
However, it is not supported, so I need to use a workaround, one more column and three constraints instead of one, as follows:
然而,该语句并不被支持,所以必须采用其他办法——多增加一列约束,使用3个而不是1个约束,如下所示:
ALTER TABLE Data.Curcuits
ADD CONSTRAINT UNQ_Curcuits UNIQUE(CurcuitID, MaximumCurrent);
GO
ALTER TABLE Data.Devices ADD CurcuitMaximumCurrent INT NULL;
GO
ALTER TABLE Data.Devices DROP CONSTRAINT FK_Devices_Curcuits;
GO
ALTER TABLE Data.Devices ADD CONSTRAINT FK_Devices_Curcuits
FOREIGN KEY(CurcuitID, CurcuitMaximumCurrent)
REFERENCES Data.Curcuits(CurcuitID, MaximumCurrent)
ON UPDATE CASCADE;
GO
ALTER TABLE Data.Devices
ADD CONSTRAINT CHK_Devices_SufficientCurcuitMaximumCurrent
CHECK(CurcuitMaximumCurrent >= MaximumCurrent);
GO
You can verify that the constraints work:
你可以验证该约束有效:
INSERT INTO Data.Devices(DeviceID,
CurcuitID,
MaximumCurrent,
CurcuitMaximumCurrent,
Description)
SELECT 1, 1, 50, 25, 'Electric car charger'
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "CHK_Devices_SufficientCurcuitMaximumCurrent". The conflict occurred in database "Test", table "data.Devices".
The statement has been terminated.
INSERT 语句和CHECK约束"CHK_Devices_SufficientCurcuitMaximumCurrent"发生冲突。 该冲突发生在数据库"Test"的"data.Devices"表。
该语句被终止执行。
As you have seen, the implementation of a very simple and very common business rule is quite involved, because such business rules are not directly supported by the database engine.
可以看出,一个非常简单而普通的业务规则实现起来也相当繁杂,因为数据库引擎并不直接支持这种业务规则。
When you want to create constraints on indexed views
在索引视图上创建约束
Even when your database guarantees that “the maximum current of your device cannot exceed the maximum current of the circuit you plug it into”, it is not good enough. Consider the following sample data:
尽管数据库保证“您的设备的最大电流不能超过您插入到它的电路的最大电流”,但这还不够。请看下列示例数据:
INSERT INTO Data.Devices(DeviceID,
CurcuitID,
MaximumCurrent,
CurcuitMaximumCurrent,
Description)
SELECT 2, 1, 15, 25, 'ShopVac';
INSERT INTO Data.Devices(DeviceID,
CurcuitID,
MaximumCurrent,
CurcuitMaximumCurrent,
Description)
SELECT 3, 1, 15, 25, 'Miter Saw';
The database structure allows to plug more than one device into a circuit, which is correct, but if you turn both devices on, their combined maximum current exceeds the circuit's maximum current. To enforce this business rule, it would be natural to create an indexed view, so that the database guarantees that the totals are always correct:
数据库中的数据表明可以插入一个以上的设备到电路,这没有错,可是当所有的设备都打开时,它们的最大电流之和会超过电路最大电流。为了加强这个业务规则,很自然的会创建一个索引视图以使数据库保证电流之和总是正确的。
CREATE VIEW Data.TotalMaximumCurrentPerCircuit WITH SCHEMABINDING
AS
SELECT d.CurcuitID,
c.MaximumCurrent AS CircuitMaximumCurrent,
SUM(d.MaximumCurrent) AS TotalMaximumCurrent,
COUNT_BIG(*) AS NumDevices
FROM Data.Devices d JOIN Data.Curcuits c ON d.CurcuitID = c.CurcuitID
GROUP BY d.CurcuitID, c.MaximumCurrent;
GO
CREATE UNIQUE CLUSTERED INDEX Data_TotalMaximumCurrentPerCircuit
ON Data.TotalMaximumCurrentPerCircuit(CurcuitID);
GO
If I could create a check constraint on that indexed view, I would be all set:
如果能在该索引视图上创建一个约束,我将进行这样的设置:
ALTER VIEW Data.TotalMaximumCurrentPerCircuit
ADD CONSTRAINT CHK_TotalMaximumCurrentPerCircuit_ValidCurcuit
CHECK(TotalMaximumCurrent <= CircuitMaximumCurrent)
Instead, I need to use triggers or rather contrived kludges. A built in native support for such quite common business rules would increase the usefulness of SQL Server.
实际上,我必须使用触发器或者精心拼凑Check约束来实现。如果数据库内置支持这种相当普遍的业务规则,那将会增加SQL Server的实用性 。


猜你喜欢
- asp替换函数如下:Function ReplaceNoIgnoreCase(str,replStr) &n
- Django Form 实时从数据库中获取数据 ,具体内容如下所示:修改 models.py 添加class UserType(models
- 今天早上到现在,一直在搞一个很愚蠢的问题,竟然一直没发现 如果$str=""; $str = "$str-$s
- 代码如下:import functoolsdef memoize(fn): print('start memoize
- 连接分为:内连接、外连接、交叉连接 一、内连接——最常用 定义:仅将两个表中满足连接条件的行组合起来作为结果集。 在内连接中,只有在两个表中
- String Types(字符串类型)字符串类型Mysql支持多种字符串类型的变体。 这些数据类型在4.1和5.0版本中有较大的变化, 这使
- 前言如何通过python实现邮件解析?邮件的格式十分复杂,主要是mime协议,本文主要是从实现出发,具体原理可以自行研究。一、安装通过mai
- 推荐阅读:JS iFrame加载慢怎么解决在项目中经常要动态添加iframe,然后再对添加的iframe进行相关操作,而往往iframe还没
- 前言通过pandas的使用,我们经常要交互式地展示表格(dataframe)、分析表格。而表格的格式就显得尤为重要了,因为大部分时候如果我们
- QQ影音新版发布官网Banner经过两周的酝酿、脑爆与设计调整,于20日顺利上线,连续7天,经历了昨天激动人心的最后发布,到此告一段落,这里
- 很多时候,我发现自己需要进行生成报告、输出文件或字符串的任务。它们或多或少都会遵循某种模式,通常这些模式是如此相似,以至于我们希望拥有一个可
- *args与**kwarsg及闭包和装饰器过程先理解闭包,再理解装饰器,不要忘了不定长参数def func():
- 一、PIL的基本概念:PIL中所涉及的基本概念有如下几个:通道(bands)、模式(mode)、尺寸(size)、坐标系统(coordina
- 1.打开文件:f=open(r'E:\PythonProjects\test7\a.txt',mode='rt
- 1、#coding:utf-8chose = [ ('foo',1,2), ('bar
- 本文实例为大家分享了python opencv进行图像拼接的具体代码,供大家参考,具体内容如下思路和方法思路1、提取要拼接的两张图片的特征点
- 使用cv2.imread(),cv2.imshow(),cv2.imwrite()读取、显示和保存图像一、读入图像使用函数cv2.imrea
- 场景我们一般没必要过度优化 Go 程序性能。但是真正需要时,Go 提供的 pprof 工具能帮我们快速定位到问题。比如,我们团队之前有一个服
- mysql安装启动两种方法如下所示:方法一(简单版):1.cmd进入mysql安装的bin目录:mysqld.exe –install2.n
- 如下所示:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional