SQLAuthority.com SQL Server Important Guidelines SQLServer Guide Lines

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 9

 
1© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
INDEX
GuidelinesforSQLSERVER
1ImportantGuidelinesforSQLServer…………………………..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
NormalizeDatabasestructurebasedon3rdNormalizationForm.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
INNERJOINEmployeeeONe.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.
If“OneTable”references“AnotherTable”thanthecolumnnameusedinreference
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,asitwon’timpacttheperformance.
DonotusewildcardcharactersatthebeginningofwordwhilesearchusingLIKE
keywordasitresultsinIndexscan.
Indentcodeforbetterreadability.(Example)
WhileusingJOINsinyourSQLqueryalwaysprefixcolumnnamewiththetablename.
(Example).IfadditionallyrequirethenprefixTablenamewithServerName,
DatabaseName,DatabaseOwner.(Example)
Defaultconstraintmustbedefinedatthecolumnlevel.Allotherconstraintsmustbe
definedatthetablelevel.(ReadMoreHere)
Avoidusingrulesofdatabaseobjectsinsteaduseconstraints.
DonotusetheRECOMPILEoptionforStoredProcedureasitreducestheperformance.
AlwaysputtheDECLAREstatementsatthestartingofthecodeinthestoredprocedure.
Thiswillmakethequeryoptimizertoreusequeryplans.(Example)
PuttheSETstatementsinbeginning(afterDECLARE)beforeexecutingcodeinthe
storedprocedure.(Example)
UseBEGIN…ENDblocksonlywhenmultiplestatementsarepresentwithinaconditional
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)
Ifthereisnoneedofresultsetthenusesyntaxthatdoesn’treturnaresultset.
IFEXISTS(SELECT1
 FROMUserDetails
 WHEREUserID=50)
Ratherthan,
IFEXISTS(SELECTCOUNT(UserID)
  FROMUserDetails
 WHEREUserID=50)
UsegraphicalexecutionplaninQueryAnalyzerorSHOWPLAN_TEXTor
SHOWPLAN_ALLcommandstoanalyzeSQLqueries.Yourqueriesshoulddoan“Index
Seek”insteadofan“IndexScan”ora“TableScan”.(ReadMoreHere)
Donotprefixstoredprocedurenameswith“SP_”,as“SP_”isreservedforsystem
storedprocedures.
Example:
SP<AppName>_[<GroupName>_]<Action><table/logicalinstance>
 
7© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
Incorporateyourfrequentlyrequired,complicatedjoinsandcalculationsintoaviewso
thatyoudon’thavetorepeatthosejoins/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
ORDERBY2
Example:CorrectStatement
SELECT UserID,UserName,Password
FROM UserDetails
ORDERBYUserName
ToavoidtripsfromapplicationtoSQLServer,weshouldretrivemultipleresultsetfrom
singleStoredProcedureinsteadofusingoutputparam.
TheRETURNstatementismeantforreturningtheexecutionstatusonly,butnotdata.If
youneedtoreturndata,useOUTPUTparameters.
Ifstoredprocedurealwaysreturnssinglerowresultset,thenconsiderreturningthe
resultsetusingOUTPUTparametersinsteadofSELECTstatement,asADOhandles
OUTPUTparametersfasterthanresultsetsreturnedbySELECTstatements.
Effectiveindexesareoneofthebestwaystoimproveperformanceinadatabase
application.
BULKINSERTcommandhelpstoimportadatafileintoadatabasetableorviewin
auserspecifiedformat.
 
9© Copyright 2000-2008
Pinal Dave.
All Rights Reserved.
SQLAuthority.com
UsePolicyManagementtomakeordefineandenforceyourownpoliciesfro
configuringandmanagingSQLServeracrosstheenterprise,eg.PolicythatPrefixesfor
storedproceduresshouldbesp.
Usesparsecolumnstoreducethespacerequirementsfornullvalues.(ReadMoreHere)
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;

Navigation menu