Anda di halaman 1dari 9

1

Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

INDEX
GuidelinesforSQLSERVER
1 ImportantGuidelinesforSQLServer..2

Notice:
Allrightsreservedworldwide.Nopartofthisbookmaybereproducedorcopiedor
translatedinanyformbyanyelectronicormechanicalmeans(includingphotocopying,
recording,orinformationstorageandretrieval)withoutpermissioninwritingfromthe
publisher,exceptforreadingandbrowsingviatheWorldWideWeb.Usersarenotpermitted
tomountthisfileonanynetworkservers.

Formoreinformationsendemailto:pinal@sqlauthority.com


2
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

ImportantGuidelinesforSQLSERVER
Use"Pascal"notationforSQLserverObjectsLikeTables,Views,StoredProcedures.
Alsotablesandviewsshouldhaveending"s".
Example:
UserDetails
Emails

Ifyouhavebigsubsetoftablegroupthanitmakessensetogiveprefixforthistable
group.Prefixshouldbeseparatedby_.
Example:
Page_UserDetails
Page_Emails

UsefollowingnamingconventionforStoredProcedure.sp<Application
Name>_[<groupname>_]<actiontype><tablenameorlogicalinstance>Whereaction
is:Get,Delete,Update,Write,Archive,Insert...i.e.verb
Example:
spApplicationName_GetUserDetails
spApplicationName_UpdateEmails

UsefollowingNamingpatternfortriggers:TR_<TableName>_<action><description>
Example:
TR_Emails_LogEmailChanges
TR_UserDetails_UpdateUserName

Indexes:IX_<tablename>_<columnsseparatedby_>
Example:
IX_UserDetails_UserID

PrimaryKey:PK_<tablename>
Example:
PK_UserDetails
PK_Emails


3
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

ForeignKey:FK_<tablename_1>_<tablename_2>
Example:
FK_UserDetails_Emails

Default:DF_<tablename>_<columnname>
Example:
DF_UserDetails_UserName

NormalizeDatabasestructurebasedon3
rd
NormalizationForm.Normalizationisthe
processofdesigningadatamodeltoefficientlystoredatainadatabase.(ReadMore
Here)

AvoiduseofSELECT*inSQLqueries.Insteadpracticewritingrequiredcolumnnames
afterSELECTstatement.
Example:
SELECT Username,Password
FROM UserDetails

AvoidusingtemporarytablesandderivedtablesasitusesmoredisksI/O.Insteaduse
CTE(CommonTableExpression);itsscopeislimitedtothenextstatementinSQLquery.
(ReadMoreHere)

UseSETNOCOUNTONatthebeginningofSQLBatches,StoredProceduresandTriggers.
ThisimprovestheperformanceofStoredProcedure.(ReadMoreHere)

ProperlyformatSQLqueriesusingindents.
Example:WrongFormat
SELECTUsername,PasswordFROMUserDetailsudINNERJOIN EmployeeeON
e.EmpID=ud.UserID

Example:CorrectFormat
SELECT Username,Password
FROM UserDetailsud
INNERJOIN EmployeeeONe.EmpID=ud.UserID


4
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

PracticewritingUpperCaseforallSQLkeywords.
Example:
SELECT,UPDATE,INSERT,WHERE,INNERJOIN,AND,OR,LIKE.

TheremustbePRIMARYKEYinallthetablesofdatabasewithcolumnnameID.Itis
commonpracticetousePrimaryKeyasIDENTITYcolumn.

IfOneTablereferencesAnotherTablethanthecolumnnameusedinreference
shouldusethefollowingrule:
ColumnofAnotherTable:<OneTableName>ID
Example:
IfUsertablereferencesEmployeetablethanthecolumnnameusedinreferenceshould
beUserIDwhereUseristablenameandIDprimarycolumnofUsertableandUserIDis
referencecolumnofEmployeetable.

ColumnswithDefaultvalueconstraintshouldnotallowNULLs.

PracticeusingPRIMARYkeyinWHEREconditionofUPDATEorDELETEstatementsas
thiswillavoiderrorpossibilities.

Alwayscreatestoredprocedureinsamedatabasewhereitsrelevanttableexists
otherwiseitwillreducenetworkperformance.

AvoidserversideCursorsasmuchaspossible,insteaduseSELECTstatement.Ifyou
needtousecursorthenreplaceitwithWHILEloop(orreadnextsuggestion).

InsteadofusingLOOPtoinsertdatafromTableBtoTableA,trytouseSELECT
statementwithINSERTstatement.(ReadMoreHere)

INSERTINTOTableA(column1,column2)
SELECTcolumn1,column2
FROMTableB
WHERE.


5
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Avoidusingspaceswithinthenameofdatabaseobjects;thismaycreateissueswith
frontenddataaccesstoolsandapplications.Ifyouneedspacesinyourdatabaseobject
namethenwillaccessingitsurroundthedatabaseobjectnamewithsquarebrackets.
Example:
[OrderDetails]

Donotusereservedwordsfornamingdatabaseobjects,asthatcanleadtosome
unpredictablesituations.(ReadMoreHere)

Practicewritingcommentsinstoredprocedures,triggersandSQLbatches,whenever
somethingisnotveryobvious,asitwontimpacttheperformance.

DonotusewildcardcharactersatthebeginningofwordwhilesearchusingLIKE
keywordasitresultsinIndexscan.

Indentcodeforbetterreadability.(Example)

WhileusingJOINsinyourSQLqueryalwaysprefixcolumnnamewiththetablename.
(Example).IfadditionallyrequirethenprefixTablenamewithServerName,
DatabaseName,DatabaseOwner.(Example)

Defaultconstraintmustbedefinedatthecolumnlevel.Allotherconstraintsmustbe
definedatthetablelevel.(ReadMoreHere)

Avoidusingrulesofdatabaseobjectsinsteaduseconstraints.

DonotusetheRECOMPILEoptionforStoredProcedureasitreducestheperformance.

AlwaysputtheDECLAREstatementsatthestartingofthecodeinthestoredprocedure.
Thiswillmakethequeryoptimizertoreusequeryplans.(Example)

PuttheSETstatementsinbeginning(afterDECLARE)beforeexecutingcodeinthe
storedprocedure.(Example)

UseBEGINENDblocksonlywhenmultiplestatementsarepresentwithinaconditional
codesegment.(ReadMoreHere)


6
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Toexpressapostrophewithinastring,nestsinglequotes(twosinglequotes).
Example:
SET@sExample='SQL''sAuthority'

Whenworkingwithbranchconditionsorcomplicatedexpressions,useparenthesisto
increasereadability.
Example:
IF((SELECT1
FROMTableName
WHERE1=2)ISNULL)

Tomarksinglelineascommentuse()beforestatement.Tomarksectionofcodeas
commentuse(/*...*/).

Avoidtheuseofcrossjoinsifpossible.(ReadMoreHere)

Ifthereisnoneedofresultsetthenusesyntaxthatdoesntreturnaresultset.
IFEXISTS(SELECT 1
FROM UserDetails
WHERE UserID=50)

Ratherthan,
IFEXISTS(SELECT COUNT(UserID)
FROM UserDetails
WHERE UserID=50)

UsegraphicalexecutionplaninQueryAnalyzerorSHOWPLAN_TEXTor
SHOWPLAN_ALLcommandstoanalyzeSQLqueries.YourqueriesshoulddoanIndex
SeekinsteadofanIndexScanoraTableScan.(ReadMoreHere)

DonotprefixstoredprocedurenameswithSP_,asSP_isreservedforsystem
storedprocedures.
Example:
SP<AppName>_[<GroupName>_]<Action><table/logicalinstance>


7
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Incorporateyourfrequentlyrequired,complicatedjoinsandcalculationsintoaviewso
thatyoudonthavetorepeatthosejoins/calculationsinallyourqueries.Instead,just
selectfromtheview.(ReadMoreHere)

Donotquery/manipulatethedatadirectlyinyourfrontendapplication,insteadcreate
storedprocedures,andletyourapplicationstoaccessstoredprocedure.

Avoidusingntext,text,andimagedatatypesinnewdevelopmentwork.Usenvarchar
(max),varchar(max),andvarbinary(max)instead.

Donotstorebinaryorimagefiles(BinaryLargeObjectsorBLOBs)insidethedatabase.
Instead,storethepathtothebinaryorimagefileinthedatabaseandusethatasa
pointertotheactualfilestoredonaserver.

UsetheCHARdatatypeforanonnullablecolumn,asitwillbethefixedlengthcolumn,
NULLvaluewillalsoblockthedefinedbytes.

AvoidusingdynamicSQLstatements.DynamicSQLtendstobeslowerthanstaticSQL,
asSQLServergenerateexecutionplaneverytimeatruntime.

MinimizetheuseofNulls.Becausetheyincurmorecomplexityinqueriesandupdates.
ISNULLandCOALESCEfunctionsarehelpfulindealingwithNULLvalues

UseUnicodedatatypes,likeNCHAR,NVARCHARorNTEXTifitneeded,astheyuse
twiceasmuchspaceasnonUnicodedatatypes.

AlwaysusecolumnlistinINSERTstatementsofSQLqueries.Thiswillavoidproblem
whentablestructurechanges.

Performallreferentialintegritychecksanddatavalidationsusingconstraintsinsteadof
triggers,astheyarefaster.Limittheuseoftriggersonlyforauditing,customtasks,and
validationsthatcannotbeperformedusingconstraints.

Alwaysaccesstablesinthesameorderinallstoredprocedureandtriggersconsistently.
Thiswillavoiddeadlocks.(ReadMoreHere)


8
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

Donotcallfunctionsrepeatedlyinstoredprocedures,triggers,functionsandbatches,
insteadcallthefunctiononceandstoretheresultinavariable,forlateruse.

WithBeginandEndTransactionalwaysuseglobalvariable@@ERROR,immediately
afterdatamanipulationstatements(INSERT/UPDATE/DELETE),sothatifthereisan
Errorthetransactioncanberollback.

ExcessiveusageofGOTOcanleadtohardtoreadandunderstandcode.

DonotusecolumnnumbersintheORDERBYclause;itwillreducethereadabilityofSQL
query.
Example:WrongStatement
SELECT UserID,UserName,Password
FROM UserDetails
ORDERBY 2

Example:CorrectStatement
SELECT UserID,UserName,Password
FROM UserDetails
ORDERBY UserName

ToavoidtripsfromapplicationtoSQLServer,weshouldretrivemultipleresultsetfrom
singleStoredProcedureinsteadofusingoutputparam.

TheRETURNstatementismeantforreturningtheexecutionstatusonly,butnotdata.If
youneedtoreturndata,useOUTPUTparameters.

Ifstoredprocedurealwaysreturnssinglerowresultset,thenconsiderreturningthe
resultsetusingOUTPUTparametersinsteadofSELECTstatement,asADOhandles
OUTPUTparametersfasterthanresultsetsreturnedbySELECTstatements.

Effectiveindexesareoneofthebestwaystoimproveperformanceinadatabase
application.

BULKINSERTcommandhelpstoimportadatafileintoadatabasetableorviewin
auserspecifiedformat.


9
Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com

UsePolicyManagementtomakeordefineandenforceyourownpoliciesfro
configuringandmanagingSQLServeracrosstheenterprise,eg.PolicythatPrefixesfor
storedproceduresshouldbesp.

Usesparsecolumnstoreducethespacerequirementsfornullvalues.(ReadMoreHere)

UseMERGEStatementtoimplementmultipleDMLoperationsinsteadofwriting
separateINSERT,UPDATE,DELETEstatements.

Whensomeparticularrecordsareretrievedfrequently,applyFilteredIndextoimprove
queryperformace,fasterretrievalandreduceindexmaintenancecosts.

UsingtheNOLOCKqueryoptimizerhintisconsideredgoodpracticeinordertoimprove
concurrencyonabusysystem.

EXCEPTorNOTEXISTclausecanbeusedinplaceofLEFTJOINorNOTINforbetter
peformance.
Example:
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salary>1000ANDSalary
NOTIN(SELECT Salary
FROM EmployeeRecord
WHERE Salary>2000);

(Recomended)
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salery>1000
EXCEPT
SELECT EmpNo,EmpName
FROM EmployeeRecord
WHERE Salery>2000
ORDERBY EmpName;

Anda mungkin juga menyukai