SQL Server约束增强的两点建议

在许多情况下,对外键使用更复杂的逻辑表达式是非常有用的。 此外,在某些情况下能够在索引视图创建约束也将非常实用。 我将举例说明,同时我希望针对此文的投票链接会尽快加上。
当外键中需要更为复杂的逻辑表达式时
考虑下面的简单常识: 您的设备的最大电流不能超过您插入到它的电路的最大电流。 假设下面的表存储电路和设备数据:


代码如下:

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的实用性 。

(0)

相关推荐

  • MySQL学习笔记4:完整性约束限制字段

    完整性约束是对字段进行限制,从而符合该字段达到我们期望的效果比如字段含有默认值,不能是NULL等 直观点说:如果插入的数据不满足限制要求,数据库管理系统就拒绝执行操作 设置表的主键 主键能够标识表中每条信息的唯一性,如同身份证号码和人的关系 人可以同名,但是身份证号码却是唯一的, 创建主键的目的在于快速查找到表中的某一条信息 单字段主键 复制代码 代码如下: mysql> create table student( -> id int primary key, -> name varch

  • MySQL 添加、修改、删除表的列及约束等表的定义

    ALTER TABLE:添加,修改,删除表的列,约束等表的定义. 查看列:desc 表名; 修改表名:alter table t_book rename to bbb; 添加列:alter table 表名 add column 列名 varchar(30); 删除列:alter table 表名 drop column 列名; 修改列名MySQL: alter table bbb change nnnnn hh int; 修改列名SQLServer:exec sp_rename't_stude

  • 使用sql语句创建和删除约束示例代码

    使用sql语句创建和删除约束 约束类型 主键约束(Primary Key constraint) --:要求主键列数据唯一,并且不允许为空. 唯一约束(Unique constraint) --:要求该列唯一,允许为空,但只能出现一个空值. 检查约束(Check constraint) --:某列取值范围限制,格式限制等,如有关年龄.邮箱(必须有@)的约束. 默认约束(Default constraint) --:某列的默认值,如在数据库里有一项数据很多重复,可以设为默认值. 外键约束(Fore

  • sql语句查询数据库中的表名/列名/主键/自动增长值实例

    sql语句查询数据库中的表名/列名/主键/自动增长值 ----查询数据库中用户创建的表 ----jsj01 为数据库名 select name tablename from jsj01..sysobjects where type='U' and name not in ('dtproperties') --查询表里的字段信息 ---docs为表名 ---- select * from syscolumns where id = object_id('docs') ----查询数据库中所有类型

  • sql脚本查询数据库表,数据,结构,约束等操作的方法

    1.查询当前数据库所有表 复制代码 代码如下: SELECT     O.object_id AS TableId,    TableName=O.name  ,    TableDesc= O.type FROM sys.columns C    INNER JOIN sys.objects O        ON C.[object_id]=O.[object_id]            AND O.type='U'            AND O.is_ms_shipped=0   

  • mysql创建Bitmap_Join_Indexes中的约束与索引

    测试过程如下:create table sales  as select * from sh.sales: create table customers as  select * from sh.customers: create unique index CUST_ID_un on customers(CUST_ID); 创建: Bitmap Join Indexes create bitmap index sales_cust_gender_bjix on sales(customers.c

  • MySQL导出所有Index和约束的方法

    本文汇总了MySQL导出所有Index 和 约束的方法,提供给大家以方便大家查询使用.具体如下: 1. 导出创建自增字段语句: SELECT CONCAT( 'ALTER TABLE `', TABLE_NAME, '` ', 'MODIFY COLUMN `', COLUMN_NAME, '` ', IF(UPPER(DATA_TYPE) = 'INT', REPLACE( SUBSTRING_INDEX( UPPER(COLUMN_TYPE), ')', 1 ), 'INT', 'INTEG

  • sqlserver 修改列名及表名的sql语句

    代码如下: EXEC sp_rename '表名.[原列名]', '新列名', 'column' Transact-SQL 参考 sp_rename 更改当前数据库中用户创建对象(如表.列或用户定义数据类型)的名称. 语法 sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name' [ , [ @objtype = ] 'object_type' ] 参数 [@objname =] 'object_name' 是用户对象(

  • Mysql中返回一个数据库的所有表名,列名数据类型备注

    desc 表名; show columns from 表名; describe 表名; show create table 表名; use information_schema select * from columns where table_name='表名'; 顺便记下: show databases; 也可以这样 use information_schema select table_schema,table_name from tables where table_schema='数据

  • SQLSERVER实现更改表名,更改列名,更改约束代码

    废话不多说了,具体详情如下所示: 1.修改表名 格式:sp_rename tablename,newtablename sp_rename tablename,newtablename 2.修改字段名 格式:sp_rename 'tablename.colname',newcolname,'column' sp_rename 'tablename.colname',newcolname,'column' 3.添加字段 格式:alter table table_name add new_colum

随机推荐