數據完整性(Data Integrity)筆記


因數據庫存儲數據要持之以恆,數據庫中的表需要一些方法驗證各種數據類型。不僅僅局限於數據類型,還有唯一值,值的范圍,或者某列的值和另外一個表中的列匹配。

當你在定義表的時候其用這些數據驗證方法。這叫做聲明數據完整性。也就是我們說的表約束。

USE tempdb
GO
CREATE TABLE s
    (
      sid VARCHAR(20) ,
      sname VARCHAR(20) ,
      ssex VARCHAR(2) CHECK ( ssex = ''
                              OR ssex = '' )
                      DEFAULT '' ,
      sage INT CHECK ( sage BETWEEN 0 AND 100 ) ,
      sclass VARCHAR(20) UNIQUE ,
      CONSTRAINT PK_s PRIMARY KEY ( sid, sclass )
    )
CREATE TABLE t
    (
      teacher VARCHAR(20) PRIMARY KEY ,
      sid VARCHAR(20) NOT NULL ,
      sclass VARCHAR(20) NOT NULL ,
      num INT ,
      FOREIGN KEY ( sid, sclass ) REFERENCES s ( sid, sclass )
    )


主鍵約束 Primary Key Constraints

primary key = unique constraint + not null constraint

創建主鍵約束時,數據庫自動創建唯一索引,默認為聚集索引

創建方法一

-- Primary Key Constraints
CREATE TABLE Production.Categories
(
  categoryid   INT           NOT NULL IDENTITY,
  categoryname NVARCHAR(15)  NOT NULL,
  description  NVARCHAR(200) NOT NULL,
  CONSTRAINT PK_Categories PRIMARY KEY(categoryid)
);

創建方法二

USE TSQL2012;
ALTER TABLE Production.Categories 
    ADD CONSTRAINT PK_Categories PRIMARY KEY(categoryid);
GO

列出數據庫中的主鍵約束

-- To list the primary key constraints in a database, you can query the sys.key_constraints table filtering on a type of PK:
SELECT * 
FROM sys.key_constraints 
WHERE type = 'PK';


唯一性約束 Unique Constraints

僅可以有一行為NULL,ORACLE中可以有多行列值為NULL。

創建唯一鍵約束時,數據庫自動創建唯一索引,默認為非聚集索引

在保證數據唯一性上,唯一索引、唯一約束並沒有區別,那么應該使用約束還是索引?

約束定義通常出現在數據庫邏輯結構設計階段,即定義表結構時,索引定義通常出現在數據庫物理結構設計/查詢優化階段。

從功能上來說唯一約束和唯一索引沒有區別,但在數據庫維護上則不太一樣,對於唯一約束可以用唯一索引代替,以方便維護,但是主鍵約束則沒法代替。

ALTER TABLE Production.Categories 
    ADD CONSTRAINT UC_Categories UNIQUE (categoryname);
GO

列出數據庫中的唯一約束

SELECT * 
FROM sys.key_constraints 
WHERE type = 'UQ';


外鍵 Foreign Key Constraints

創建

ALTER TABLE Production.[Products]  WITH CHECK 
    ADD  CONSTRAINT [FK_Products_Categories] FOREIGN KEY(categoryid)
    REFERENCES Production.Categories (categoryid)

查找外鍵

SELECT *
FROM sys.foreign_keys
WHERE name = 'FK_Products_Categories';

刪除外鍵

ALTER TABLE Production.Products DROP CONSTRAINT FK_Products_Categories;


檢查約束 Check Constraints

創建

ALTER TABLE Production.Products WITH CHECK
ADD CONSTRAINT CHK_Products_unitprice
CHECK (unitprice>=0);
GO
ALTER TABLE dbo.NewTable 
ADD ZipCode INT NULL 
CONSTRAINT CHK_ZipCode 
CHECK (ZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]');

查找檢查約束

SELECT *
FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID(N'Production.Products', N'U');


默認約束 Default Constraints

創建

CREATE TABLE Production.Products
(
  productid    INT          NOT NULL IDENTITY,
  productname  NVARCHAR(40) NOT NULL,
  supplierid   INT          NOT NULL,
  categoryid   INT          NOT NULL,
  unitprice    MONEY        NOT NULL
    CONSTRAINT DFT_Products_unitprice DEFAULT(0),
  discontinued BIT          NOT NULL 
    CONSTRAINT DFT_Products_discontinued DEFAULT(0),
);

查找

SELECT * 
FROM sys.default_constraints
WHERE parent_object_id = OBJECT_ID(N'Production.Products', 'U');


啟用和禁用約束檢查

ALTER TABLE Products NOCHECK CONSTRAINT CHK_Price;
ALTER TABLE Products CHECK CONSTRAINT CHK_Price;


檢查在SQL Server中的約束

--Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function... 
IF OBJECT_ID('CK_ConstraintName', 'C') IS NOT NULL 
    ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
--OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results. 
IF OBJECT_ID('CK_ConstraintName') IS NOT NULL 
    ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName
--OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:
--Constraint Object Types:
--•C = CHECK constraint
--•D = DEFAULT (constraint or stand-alone)
--•F = FOREIGN KEY constraint
--•PK = PRIMARY KEY constraint
--•R = Rule (old-style, stand-alone)
--•UQ = UNIQUE constraint

 

參考文章

09. 約束與索引的聯系


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM