Constraints fall into the following categories:
1) non-null constraints, using the not nulls keyword;
2) Default value constraints, using default keyword;
3) Check the constraints, use the CHECK keyword;
4) Unique constraints, using the unique keyword;
5) Primary KEY constraint, using primary key keyword;
6) FOREIGN KEY constraint, use foreign key keyword.
The constraint is to ensure the integrity of the data, which prevents data that you do not want to insert into the input.
The following is a demonstration using a SQL code:
UsePersonInfo--using the Personinfo databaseGOIF EXISTS(SELECT * fromSys.tablesWHERE [name] = 'Employee')--If there is an employee this tableDROP TABLEEmployee--the DeleteGOIF EXISTS(SELECT * fromSys.tablesWHERE [name] = ' Person')--If there is a person this tableDROP TABLEPerson--the DeleteGOCREATE TABLEPerson--Create person (people) Table( --IndexPersonIDint IDENTITY(1,1) not NULL CONSTRAINTPk_personidPRIMARY KEY,--creates an integer, self-increment 1, identity seed of 1, not allowed to be empty, constraint is a PRIMARY KEY constraint for the column PersonID --nameNamenvarchar( -) not NULL,--Create a column with Unicode non-fixed length (up to 20 Unicode characters stored) name --AgeAgeint not NULL CONSTRAINTCk_ageCHECK(age>= - andAge<= -) ,--Create an integer that constrains the check constraint to a column age --SexGenderbit not NULL CONSTRAINTDf_genderDEFAULT(1) ,--Create a column of type bit with a default value of 1 (True) gender --Identity Information [Identity] nchar( -) not NULL CONSTRAINTCk_identityCHECK(LEN([Identity])= -) CONSTRAINTUq_identityUNIQUE --creates a non-Unicode, non-fixed-length (up to 18 non-Unicode characters) constraint for the column identity of the CHECK constraint)GO CREATE TABLEEmployee--Create employee (Employee) Table( --IndexEmployeeIDint IDENTITY(1,1001) not NULL CONSTRAINTpk_idPRIMARY KEY,--creates an integer, self-increment 1, identity seed of 1001, not allowed to be empty, constraint is a PRIMARY KEY constraint for the column EmployeeID --People indexPersonIDint not NULL CONSTRAINTFk_personidFOREIGN KEY REFERENCESPerson (PersonID),--Job TitlePostnvarchar( -) not NULL,--Create a column post with Unicode non-fixed length (up to 20 Unicode characters stored) --Time of entryEntrytimedatetime CONSTRAINTDf_entrytimeDEFAULT getdate()--Create a column of type datetime with default value of server time Entrytime)GO
Results:
1-sql Server 2008 Using SQL statements to create a table with constraints