The previous section is about adding conditional constraints directly when creating a table, but how do you do this when you add conditional constraints after the table is created?
In fact, with the SQL code written in the previous section, a lot is the same, just use the ALTER keyword to modify the table and add the constraint constraint keyword only, other similar.
The code is as follows:
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,--Create an integer, increment to 1, identify the column with seed 1, not allowed to be empty PersonID --nameNamenvarchar( -) not NULL,--Create a column with Unicode non-fixed length (up to 20 Unicode characters stored) name --AgeAgeint not NULL,--Create a column of an integral type age --SexGenderbit not NULL,--Create a column of type bit gender --Identity Information [Identity] nchar( -) not NULL--create a column with non-Unicode non-fixed length (up to 18 non-Unicode characters) identity)ALTER TABLE PersonADD CONSTRAINTPk_personidPRIMARY KEY(PersonID),--Create a PRIMARY KEY constraint for PersonID CONSTRAINTCk_ageCHECK(age>= - andAge<= -),--Create a CHECK constraint for age CONSTRAINTDf_genderDEFAULT(1) forGender,--Create a DEFAULT constraint for gender CONSTRAINTCk_identityCHECK(LEN([Identity])= -),--Create a CHECK constraint for identity CONSTRAINTUq_identityUNIQUE([Identity])--Create a unique constraint for identityGO CREATE TABLEEmployee--Create employee (Employee) Table( --IndexEmployeeIDint IDENTITY(1,1001) not NULL,--Create an integer, increment to 1, identify the column with seed 1001, not allowed to be empty EmployeeID --People indexPersonIDint not NULL , --Job TitlePostnvarchar( -) not NULL,--Create a column post with Unicode non-fixed length (up to 20 Unicode characters stored) --Time of entryEntrytimedatetime --Create a column of type datetime entrytime)GOALTER TABLEEmployeeADD CONSTRAINTPk_employeeidPRIMARY KEY(EmployeeID),--Create a PRIMARY KEY constraint for Emlpoyeeid CONSTRAINTFk_personidFOREIGN KEY(PersonID)REFERENCESPerson (PersonID),--Create a FOREIGN KEY constraint for PersonID CONSTRAINTDf_entrytimeDEFAULT getdate() forEntrytime--Create a DEFAULT constraint for EmlpoyeeidGO
Results:
2-sql Server 2008 Using SQL statements to add constraints to an existing table