CreatingTablesUsingT-SQL
ThissectionexamineshowtouseT-SQLtocreatetables.You
willseehowtodefinetablecolumnsandsetpropertiesforthe
columns.Alsocoveredisdefiningalocationforthetable,
addingconstraints,andmakingmodificationstoexistingtables.
DefiningColumns
Indefiningacolumn,youassignanameandadatatypetothe
column.Dependingonthedatatypeyouchoose,youmightalso
havetoassignparameterstothedatatype,suchasalengthfor
achar()column.Listing12.3showsasimpleCREATETABLE
statementdefiningsixcolumns.
Listing12.3DefiningColumnswithCREATETABLE
CREATETABLEyourdb.dbo.employee
(
Emp_noint,
Lnamevarchar(20),
Fnamevarchar(20),
Phonechar(13),
Deptsmallint,
Salarymoney
)
ColumnProperties
Columnsalsocanhavepropertiesassignedtothem.These
propertiescanaddresswhetheravaluemustbeprovidedfora
column,usingNULLorNOTNULL,orwhetherSQLServer
providesavalueforthecolumn,asisthecasewiththe
identityproperty.
NULLorNOTNULL
Whenwritingyourcreatetablescripts,itisalwaysgoodformto
explicitlystatewhetheracolumnshouldorshouldnotcontain
nulls.TheSQLServerdefaultisnottoallownulls.TheANSI-92
standardistoallownulls.Tofurtherconfusematters,the
databaseoption'ANSI_NULL_DEFAULT'canbesetsothatSQL
ServermatchestheANSI-92standard.Itcanalsobesetatthe
sessionlevel.Asamatteroffact,ifyourunyourscriptfrom
QueryAnalyzer,itoverridestheSQLServerdefaultandallows
nullsifnotspecified.IhopeI'vemademypointthatitisbestto
explicitlyspecifytheNULLpropertysoyouknowforsurewhat
it'sgoingtobe.Listing12.4expandsonthepreviousexample
andproperlyspecifiesNULLorNOTNULL.
Listing12.4DefiningColumnNULLPropertieswith
CREATETABLE
CREATETABLEyourdb.dbo.employee
(
Emp_nointNOTNULL,
Lnamechar(20)NOTNULL,
Fnamechar(20)NOTNULL,
Phonechar(13)NULL,
DeptsmallintNOTNULL,
SalaryintNULL
)
Itisbeyondthescopeofthissectiontoenterthedebateon
whethercolumnsshouldeverallownulls.Thatbeingsaid,I'llgo
aheadandputinmyadvice.IfacolumnisdefinedasNULL,no
valueneedstobeenteredinthatcolumnwheninsertingor
updatingdata.BydefiningcolumnsasNOTNULLandproviding
adefaultvaluewherepossible,yourdatawillbemore
consistentandeasiertoworkwith.Ifyouallownulls,youand
thedevelopmentteammustalwaysbeawareoftheeffectnulls
canhaveonqueryingthedatabase.
IdentityColumns
Anothercommonpropertyspecifiedwhencreatingtablesisthe
IDENTITYproperty.Thisproperty,usedinconjunctionwiththe
integerdatatypes(althoughdecimalcanbeusedwithascaleof
0),automaticallygeneratesauniquevalueforacolumn.Thisis
extremelyusefulforgeneratingwhatisreferredtoasa
surrogateprimarykey.Puristswillsaythattheprimarykey,
oruniquerowidentifier,shouldbederivedfromacolumnor
combinationofcolumnsthatarevalidattributesoftheentity.In
theemployeetableIhavebeenusingintheexamples,without
anemployeekeybeinggenerated,Iwouldhavetocombinelast
name,firstname,andphonenumberastheprimarykey.Even
then,ifJohnSmithJr.andJohnSmithSr.hadthesamephone
number,thiscombinationwouldfailtoguaranteeuniqueness.
ThisiswhereIDENTITYcomesin.Bygeneratingauniquevalue
foreachrowentered,Ihavesatisfiedtheneedforauniquekey
ontherow.
WhenimplementinganIDENTITYproperty,yousupplyaseed
andanincrement.Theseedisthestartvalueforthenumeric
count,andtheincrementistheamountbywhichitgrows.A
seedof10andanincrementof10wouldproduce10,20,30,
40,andsoon.Ifnotspecified,thedefaultseedvalueis1and
theincrementis1.Listing12.5addstothescriptbysettingan
IDENTITYvaluethatstartsat100andincrementsby10.
Listing12.5DefininganIdentityColumnwith
CREATETABLE
CREATETABLEyourdb.dbo.employee
(
Emp_nointIDENTITY(100,10)NOTNULL,
Lnamechar(20)NOTNULL,
Fnamechar(20)NOTNULL,
Phonechar(13)NULL,
DeptsmallintNOTNULL,
SalaryintNULL
)
DefiningTableLocation
Asdatabasesscaleinsize,thephysicallocationofdatabase
objects,particularlytablesandindexes,becomescrucial.
Considertwotables,EmployeeandDept,whicharealways
queriedtogether.Iftheyarelocatedonthesamephysicaldisk,
contentionforhardwareresourcesslowsperformance.SQL
Serverenablesyoutospecifywhereatable(orindex)isstored.
Thisnotonlyaffectsperformance,butplanningforbackupsas
well.Bydedicatingaread-onlytabletoafilegroup,youonly
needtobackupthefilegrouponce.Ifyourtablecontainstext
orimagedata,youcanalsospecifywhereitshouldbestored.
ThelocationofthetableisspecifiedwiththeONclause,and
TEXTIMAGEONindicateswherethetextandimagelocaters
shouldpoint.InListing12.6,youcreatetheemployeeanddept
tables,placethemontwodifferentfilegroups,andstorethe
imagefortheemployeesecurityphotoonyetanotherfilegroup.
Notethatthefilegroupsmustexistbeforethetablesare
created.Forinformationonfilegroups,seeChapter11,
"CreatingandManagingDatabases."
Listing12.6SyntaxforCreatingTableson
SpecificFilegroups
CREATETABLEyourdb.dbo.employee
(
Emp_nointIDENTITY(100,10)NOTNULL,
Lnamechar(20)NOTNULL,
Fnamechar(20)NOTNULL,
Phonechar(13)NULL,
DeptsmallintNOTNULL,
PhotoimageNULL,
SalaryintNULL
)
ONFGDISK1
TEXTIMAGE_ONFGDISK3
GO
CREATETABLEyourdb.dbo.dept
(
Dept_nosmallintIDENTITY(10,10)NOTNULL,
Namevarchar(20)NOTNULL,
Descriptionvarchar(80)NOTNULL,
Loc_codechar(2)NULL
)
ONFGDISK2
DefiningTableConstraints
Constraintsprovideuswiththemeanstoenforcedataintegrity.
InadditiontoNULL/NOTNULL,whichwascoveredinaprevious
section,SQLServerprovidesfiveconstrainttypes:PRIMARY
KEY,FOREIGNKEY,UNIQUE,CHECK,andDEFAULT.
ConstraintsarecoveredindetailinChapter14,sointhe
contextofcreatingtables,thischapterwillconcentrateonthe
syntaxforaddingconstraints.
Listing12.7expandsontheCREATETABLEscriptbyadding
primarykeystobothtablesandcreatingaforeignkeyonthe
employeetablethatreferencesthedepttable.
Listing12.7SyntaxforCreatingConstraintswith
CREATETABLE
CREATETABLEyourdb.dbo.employee
(
Emp_nointIDENTITY(100,10)CONSTRAINTEMP_PKPRIMARYKEYNO
Lnamechar(20)NOTNULL,
Fnamechar(20)NOTNULL,
Phonechar(13)NULL,
DeptsmallintCONSTRAINTEMP_DEPT_FKREFERENCESdept(dept_no)
PhotoimageNULL,
SalaryintNULL
)
ONFGDISK1
TEXTIMAGE_ONFGDISK3
go
CREATETABLEyourdb.dbo.dept
(
Dept_nosmallintIDENTITY(10,10)CONSTRAINTDEPT_PKPRIMARY
Namevarchar(20)NOTNULL,
Descriptionvarchar(80)NOTNULL,
Loc_codechar(2)NULL
)
ONFGDISK2
Inthefollowingexample,CREATETABLEisrunfirst,andthen
ALTERTABLEisruntoaddtheconstraints.Listing12.8shows
howseparatingconstraintcreationfromtablecreationmakes
thescripteasiertoreadandmoreflexible.
Listing12.8SyntaxforCreatingConstraintswith
ALTERTABLE
CREATETABLEdbo.Product(
ProductIDintIDENTITY(1,1)NOTNULL,
ProductNamenvarchar(40)NOTNULL,
SupplierIDintNULL,
CategoryIDintNULL,
QuantityPerUnitnvarchar(20)NULL,
UnitPricemoneyNULL,
UnitsInStocksmallintNULL,
UnitsOnOrdersmallintNULL,
ReorderLevelsmallintNULL,
DiscontinuedbitNOTNULL
)
GO
ALTERTABLEdbo.ProductADD
CONSTRAINTDF_Product_UnitPriceDEFAULT(0)FORUnitPrice,
CONSTRAINTPK_ProductPRIMARYKEY(ProductID),
CONSTRAINTCK_Product_UnitPriceCHECK(UnitPrice>=0)
GO
ALTERTABLEdbo.ProductADD
CONSTRAINTFK_Product_CategoriesFOREIGNKEY
(CategoryID)REFERENCESdbo.Categories(CategoryID)
GO
Adding/Removing/ModifyingTableColumns
UsingT-SQL
ThepreviousexampletouchedonusingALTERTABLEtoadd
constraintstoanexistingtable.Althoughthisisacommonuse
oftheALTERTABLEcommand,youcanactuallychangeseveral
propertiesofatable.Thefollowingliststhetypesofchanges
youcanmaketoatable:
ChangethedatatypeorNULLpropertyofacolumn.
Addnewcolumnsordropexistingcolumns.
Addordropconstraints.
EnableordisableCHECKandFOREIGNKEYconstraints.
Enableordisabletriggers.
ChangingtheDatatype
TheALTERCOLUMNclauseofALTERTABLEcanbeusedto
modifytheNULLpropertyordatatypeofacolumn.Listing12.9
showsanexampleofchangingthedatatypeofacolumn.
Listing12.9ChangingtheDatatypeofaColumn
withALTERTABLE
ALTERTABLEproduct
ALTERCOLUMNProductNamevarchar(50)
Youmustbeawareofseveralrestrictionswhenyoumodifythe
datatypeofacolumn.Thefollowingrulesapplywhenaltering
columns:
Atext,image,ntext,ortimestampcolumncan'tbe
modified.
Thecolumncan'tbetheROWGUIDCOLforthetable.
Thecolumncan'tbeacomputedcolumnorbereferenced
byacomputedcolumn.
Thecolumncan'tbeareplicatedcolumn.
Ifthecolumnisusedinanindex,thecolumnlengthcan
onlybeincreasedinsize.Inaddition,itmustbeavarchar,
nvarchar,orvarbinarydatatype,andthedatatypecannot
change.
IfstatisticshavebeengeneratedusingCREATESTATISTICS,
thestatisticsmustfirstbedropped.
Thecolumncan'thaveaPRIMARYKEYorFOREIGNKEY
constraintorbeusedinaCHECKorUNIQUEconstraint;the
exceptionisthatacolumnwithaCHECKorUNIQUE
constraint,ifdefinedasvariablelength,canhavethelength
altered.
Acolumnwithadefaultdefinedforitcanonlyhavethe
length,nullability,orprecisionandscalealtered.
Ifacolumnhasaschema-boundviewdefinedonit,the
samerulesthatapplytocolumnswithindexesapply.
NOTE
Changingsomedatatypescanresultinchangingthedata.Forexample,
changingfromnchartocharcouldresultinanyextendedcharactersbeing
converted.Similarly,changingprecisionandscalecouldresultindatatruncation.
Othermodificationssuchaschangingfromchartointmightfailifthedata
doesn'tmatchtherestrictionsofthenewdatatype.Whenchangingdatatypes,
alwaysvalidatethatthedataconformstothenewdatatype.
AddingandDroppingColumns
ColumnsareaddedtoatablewiththeADDCOLUMNclause.
Listing12.10illustratesaddingacolumntotheproducttable.
Listing12.10AddingaColumnwithALTERTABLE
ALTERTABLEproduct
ADDProdDescvarchar(100)NULL
SQLServeraddsthecolumn,andinthiscaseallowsaNULL
valueforallrows.IfNOTNULLisspecified,thenthecolumn
mustbeanidentitycolumnorhaveadefaultspecified.Note
thatevenifadefaultisspecified,ifthecolumnallowsnulls,the
columnwillnotbepopulatedwiththedefault.UsetheWITH
VALUESclausetooverridethisandpopulatethecolumnwiththe
default.
Withsomerestrictions,columnscanalsobedroppedfroma
table.ThesyntaxfordroppingacolumnisshowninListing
12.11.Multiplecolumnscanbespecified,separatedbya
comma.
Listing12.11DroppingaColumnwithALTERTABLE
ALTERTABLEproduct
DROPCOLUMNProdDesc
Thefollowingcolumnscannotbedropped:
Anindexedcolumn
Replicatedcolumns
ColumnsusedinCHECK,FOREIGNKEY,UNIQUE,orPRIMARY
KEYconstraints
Columnsassociatedwithadefaultorboundtoadefault
object
Acolumnthatisboundtoarule
NOTE
CareshouldbetakenwhenusingALTERTABLEtomodifycolumnswithexisting
data.Whenadding,dropping,ormodifyingcolumns,SQLServerplacesa
schemalockonthetable,preventinganyotheraccessuntiltheoperation
completes.Changestocolumnsintableswithmanyrowscantakealongtimeto
completeandgeneratealargeamountoflogactivity.
Youshouldbeawarethatifyouwanttochangeacolumn's
name,itisnotnecessarytodropitandthenaddanewcolumn.
Columnnamescanbechangedusingsp_rename.Aswithany
databaseobject,considertheeffectstherenamemighthaveon
otherobjectsorqueriesthatreferencethecolumn.Thesyntax
forchangingacolumnnameisEXECsp_rename'northwind.
[orderdetails]','details','COLUMN'.
Chapter11.CreatingandManaging
Databases
ByPaulJensenandRayRankins
INTHISCHAPTER
WhatMakesUpaSQLServerDatabase?
DataStorageinSQLServer
DatabaseFiles
CreatingDatabases
ManagingDatabases
SettingDatabaseOptions
Thedatabaseis,ofcourse,SQLServer'ssolereasonfor
existence.Thischapterwillexaminewhatadatabaseconsists
of,howtocreateone,andtheongoingmanagement
requirementsofadatabase.
Chapter14.ImplementingDataIntegrity
byPaulJensen
INTHISCHAPTER
TypesofDataIntegrity
EnforcingDataIntegrity
Constraints
Rules
Defaults
Ensuringtheintegrityofdataisoneofthemostimportanttasks
ofanadministrator.Keybusinessdecisionsareoftenmade
basedoninformationinthedatabase;ifthedatais
misrepresented,incorrectconclusionsmightbedrawn.Consider
acarmanufacturerwhousesaproductcodeR01(Rzeroone)
torepresenteveryredcarsold.Topredictnextyear'ssalesof
redcars,theyrunaqueryonthedatabasetocountthe
instancesofR01.Theydeterminethattheysoldfarfewerred
carsthanexpected,andreduceproduction.Halfwaythrough
theyear,theyrunoutofredcars.Oncloserinspectionofthe
data,theydeterminethattheyhadactuallysoldplentyofred
cars,butthedataentrypersonnelhadinmanycases
incorrectlyenteredthecodeasRo1(Rohone),R0l(RzeroL)
orRol(RohL).Sodoestheblamefallonthedataentry
personnel?Notlikely.Integrityconstraintstopreventincorrect
entriesarethepropersolution.Whenitcomestodataintegrity,
thebuckstopsattheadministrator'sdesk.
Thischapterfocusesonenforcingintegritythroughtheuseof
constraints,rules,anddefaults.Dataintegritycanalsobe
enforcedattheapplicationlevel,whichisasubjectforabook
onapplicationdesign,andthroughstoredproceduresand
triggers.Becausestoredproceduresandtriggershave
additionalfunctionalityoutsideofdataintegrity,theyare
coveredinseparatechaptersoftheirown.CheckoutChapter
28,"CreatingandManagingStoredProceduresinSQLServer,"
andChapter29,"CreatingandManagingTriggers"tolearn
more.
Chapter28.CreatingandManaging
StoredProceduresinSQLServer
byRayRankins
INTHISCHAPTER
AdvantagesofStoredProcedures
CreatingandExecutingStoredProcedures
DeferredNameResolution
ViewingandModifyingStoredProcedures
UsingInputParameters
UsingOutputParameters
ReturningProcedureStatus
CursorsinStoredProcedures
NestedStoredProcedures
UsingTemporaryTablesinStoredProcedures
UsingthetableDatatype
RemoteStoredProcedures
DebuggingStoredProcedureswithQueryAnalyzer
DebuggingwithMicrosoftVisualStudioandVisualBasic
SystemStoredProcedures
Stored-ProcedurePerformance
UsingDynamicSQLinStoredProcedures
AutostartProcedures
ExtendedStoredProcedures
StoredProcedureCodingGuidelinesandLimitations
AstoredprocedureisoneormoreSQLcommandsstoredina
databaseasanexecutableobject.Storedprocedurescanbe
calledinteractively,fromwithinclientapplicationcode,from
withinotherstoredprocedures,andfromwithintriggers.Parameterscanbepassedtoandreturnedfromstoredprocedures
toincreasetheirusefulnessandflexibility.Astoredprocedure
canalsoreturnanumberofresultsetsandastatuscode.
Chapter29.CreatingandManaging
Triggers
byChrisGallelli
INTHISCHAPTER
BenefitsandUsesofTriggers
CreatingTriggers
AFTERTriggers
insertedanddeletedTables
CheckingforColumnUpdates
NestedTriggers
RecursiveTriggers
EnforcingReferentialIntegritywithTriggers
INSTEADOFTriggers
Atriggerisaspecialtypeofstoredprocedurethatisexecuted
automaticallyaspartofadatamodification.Atriggeriscreated
onatableandassociatedwithoneormoreactionslinkedwitha
datamodification(INSERT,UPDATE,orDELETE).Whenoneof
theactionsforwhichthetriggerisdefinedoccurs,thetrigger
firesautomatically.Thetriggerexecuteswithinthesame
transactionspaceasthedatamodificationstatement,sothe
triggerbecomesapartofit.