SQL Server defines data integrity 6 constraints

Source: Internet
Author: User

1. Create a customer sheet

1 IF object_id('dbo. Employees','U') is  not NULL2   DROP TABLEdbo. Employees;3 4 CREATE TABLEdbo. Employees5 (6EmpidINT          not NULL,7FirstNameVARCHAR( -) not NULL,8LastNameVARCHAR( -) not NULL,9HireDate DATE not NULL,TenMgridINT         NULL, OneSsnVARCHAR( -) not NULL, ASalary Money        not NULL -);

2. PRIMARY KEY constraints

-- Primary Key ALTER TABLE dbo. Employees  ADDCONSTRAINT  pk_employees  PRIMARYKEY (empid);  

A unique index is created for the primary KEY constraint background, forcing the logical uniqueness constraint on the physical mechanism

3. Unique constraints

-- Unique ALTER TABLE dbo. Employees  ADDCONSTRAINT  unq_employees_ssn  UNIQUE(SSN);

4. Foreign KEY constraint create an order table Insert foreign key

IF object_id('dbo. Orders','U') is  not NULL  DROP TABLEdbo. Orders;CREATE TABLEdbo. Orders (OrderIDINT          not NULL, EmpidINT          not NULL, CustIDVARCHAR(Ten) not NULL, Orderts DATETIME2 not NULL, QtyINT          not NULL,  CONSTRAINTpk_ordersPRIMARY KEY(OrderID));
-- Foreign Keys ALTER TABLE dbo. Orders  ADDCONSTRAINT  fk_orders_employees  FOREIGNKEY  (empid)  REFERENCES dbo. Employees (Empid);

5.CHECK constraints

-- Check ALTER TABLE dbo. Employees  ADDCONSTRAINT  chk_employees_salary  CHECK>  0.00);

6. Default Constraints

-- Default ALTER TABLE dbo. Orders  ADDCONSTRAINT  dft_orders_orderts  DEFAULTfor  orderts; -- Cleanup DROP TABLE dbo. Orders, dbo. Employees;

SQL Server defines data integrity 6 constraints

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.