Constraints

You might also like

Download as pdf
Download as pdf
You are on page 1of 3
a Tab be rant can be defined on a column while creating a table. H can be created with the a ABLE statement. The syntax of adding a constraint a the time of ible where, sunn name is the name ofthe column on which the constraint isto be defined onstcasnt_aame isthe name of the constraint tobe created and must follow the rules for the identifier ype is the type of constraint to be added. Constraints can be divided into the following types: ao Primary Key Constrainy~ Cs primary key consi is fing ong clu ora tof urns whos aes Grate rw in bl) Tse couros re refed to 5 the primary ey Saguely Mea Uy column cannot contain NULL values sine its wsedtouiguely columns bl The primary Key constant ensures entity nea ‘You can done a primary key constant while erating the table or you can adit ale 9Y iting the table. However, ifyou define the primary key constraint aes inserig TONS: TASS Server will gve an ror if the rows contain duplicate values in the ofan the SQL Sere try constant, you new to specif a name forte constaiot If ‘name fs not specified, the SQL Server automatically assigns « name tothe consist 4.14 Managing Daibaes and Tables ent ia primary key constrint is defined on» column that already contains dat, then the crn ta i eka ase, ary opie ae found, then the primaty Key constraint ejected. The syntax of aplying the const when creating table i “fares epee {eLastEREDinowe col_nane [, col_name (, col_nase I, _nane specifies the name ofthe constrain to be create. _ dex isto be created fr the primary Key coastrai scyyereneD are keywords tht specify ifa clustered or a nonclustered .o1 name specifies the name ofthe column(s) on which the primary key constraint i fo be defined, {” § Note You will learn more about indexes in Chaper 6 | Inthe preceding example ofthe EmployeeLave table, you can ada psimaty Ney drain, while creating the table. You ca set the EmployeeID andthe LeavestanDate Selttune ofthe EmployeeLeave table as a composite primary key. You can use the following statement to apply the primary key constraint (CREATE TAB! EmployeetD int, Loavestarebate datetime CONSTRATE HEY (employeelby. LeaveStazeDatel 2 wunanResources.txployeeleave eavestartDate: on) ' ite primary The posting sttret ene Emplayse bl Th Compa ‘The proeling ate and Laveen, The mane ofthe cosa = copkLeaveStartDate. sacsond Take 15 cont Managing Dubs ond ee defined _ name is the mame ofthe constraint on which the forge ry constraint _ vane isthe name of the cohumn on whack the Sorcgs ky constr is we be enforced. cabie_cane inthe came ofthe rented table im which the primary key constr he bec specif aoo_ ane i the name of the primary ly column ofthe seated tbe on whack toe primary key constraint has been defined In the preceding example, you can wse the following statement to apply the fonrign key constrains i the ExployecLeave tbe: CoEATe TABLE Ramactavoutces Daployeetenre ‘ hich the unique constraint is tobe Eepioyees® int CORSTRAINT Skaaployee!D FOREIGN SET REFEFEREES name specifies the naene ofthe colonels) 8 Honacbesoee Wt tmplzyee (EaplovensD? sefinet. Terrestartbate cacetine COMSTRAING cptiearestastaacs| FRIST HET iamployest©, Lanvestarcbatel , Foreign Key Constoint (¢ iy A foreign consi noc one or wore coarse Soci Key) of able St ‘The preceding stent ces the Employes abe wih» cpa Son sgn a py ty cn) aati tbe on WGN 9 PY TEE EeptoyetD cokaon The nae of the const eEmploreeD sen cn dca Te oi of plying the los Ky eosin casting abe: i occa cfs Ly omit me encom m0 EA ES das in one eble depends on the data im ances table. cents TeaLE table pane ‘ name FREI HEY (coh name Ie fot name {COMSTPAIHT constratet Stee dD Serinesers cable pane (cctmme sane 1 Te teas pam f, coh pene {noob name 4 | Gin pue fcc peme |, cot_pame fe I 4.6 Marging Dates se Tos | : s ea aee varetype chec(2) OSERALIT chadeny® CHCELAST=SIES 1 nave pane eee) | ) c to multiple col 1s when itis defined at the se ection coat tn Elena lh ESAS = int canbe applied to line come Toe rrspe column, The name ofthe constraints MALES: A single chock const _ | ble level where, Default Constraint ( fi real ee cntity senatraint nena speisi be note 915 constraint to be rested. [ein ons coe males constant ale fons that define the check 10 Be made on the column. ~F not insert values for ste! ‘Only one del i a ie column cannot be an identity column. 1 ‘system-supplied valves, such as “exprosaton speifies the condi He cxnents, such as aitumetic PSH elational operators, oF ca CURRENT. USER, and user-defined vals can PS assigned as defaults. Expression ean ine LIKE, and BETWEEN. keywords, such as ‘Acheck constraint can be specified by Using the following ksywords -tne syntax of applying the defelt constant while eeating* table is: se IN: To ensure thatthe Prtues entered are from a lst of constant expressions, ~~ yo en LIKE: To ensure thatthe valves. rere in specific columns are of eral PAE: t ‘FAS can be achieved by using wildestss } Coa. nane (constant const aint sane] PETATLE (constant, wary ona jepat contest fy a range of constant expressions WY 0 the BETWEEN Ives are included in the range. vch_name {, cod_pame ty 1) BETWEEN: To spec ror The upper and lower boundary Ya Te les roaring he creation ofthe PHECK const areas follows ) re canbe created atthe eum eve ee team contain user specified search conditions w fe Iteannot contain subgueriss a vata nace pees the ae fhe oat Ue PSS * raoes not check the existing data in the table st created with the WITH NOCHECK) + esc expression spsesanxpssion leat Ae ish ean contain a NULL value, ‘option. fg _tean reference other coturnns ofthe same table. . \ Inthe example ofereating the Employect. save table, you cam insert default constraint 12 ine malta am, enn at STE nike crampe ofthe Empoyecteave table, 3unesd Se that the leave type ea dey one ofthe tree wales: CL, PL, Of Si ‘rar this, whi creating the table ypu can ae oe se the folowing statement reat he ‘default constraint: tat he check constraint using the IN Keyword for the LeaveType column { caenre, TABLE Hunannesources-Bepleyeelaae ‘You can use the following statement 10 apply He check constraint: t {oroyeetD ine ComsTRATN®, £48902 320070 TOREIGN HEY. REFERENCES cREnTe TABLE HomanRascirces Baployeeteave wp oyeede es baplovee EAPLOYeeID) q umvmstarebace dacetine COMSTRINT Tpruenvestartoate PRIART fapioyeero int Constrarit ekbepleyee > ronsrG! KEY REFERENCES Tanvestioyenid, raavestertbatel Baployeeturces Employee (Employees) + veiverndDate aacetine wo? MUL? Tenvestarebace datetine CONSTRAINT “peraavestartDate PRIARY ~ veavencasen varchar (100) LarigaphoyeetD, veavestartbate) aeveype chat (2) CORSTAAIIT, CPSC une Leaver = Leaveenddet Venwet ype Chnrpie)) cONSTRALAE cREONTIASTT (DEEAULT "FL" teaveReason varchax (100) + : ai . nut ont Managing Daca TGA? ‘4.8 Managing Databases and Tables ———— St

You might also like