gogula g. aryalingam t-sql coding standards and best practices for developers

32

Upload: kale-staggers

Post on 31-Mar-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers
Page 2: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Gogula G. Aryalingam htt p://dbantics.wordpress.com

T-SQLCoding Standards And Best Practicesfor developers

Page 3: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

RationaleWitness to totally messed up databases

Perspectives of a lot of developers regarding SQL Server (or any database system):Hostility towards SQL Server (the database system)High priority to the client applicationBack-end nature of SQL Server (the database system)Any more reasons why you do not like SQL Server?

Page 4: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Developers:

What Do You Do with SQL Server?

Page 5: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Object Naming Conventions

Page 6: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Object Naming ConventionsWhy naming conventions?

Reduces the effort needed to read and understandIncreases the fluency in identifying objects

Do you use naming conventions?

Page 7: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Object Naming ConventionsTables:

Use upper camel caseDo not use underscores to separate wordsUse the plural form of nouns

E.g.: EmailAddresses, Customers, SalesInvoices

For relationship tables combine the related tables names E.g.: StudentsCourses

Consider using Schemas (in SQL Server 2005 and later) to group related objects (in databases with large structures)

Suggestions?

Page 8: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Object Naming Conventions

Field Names:Use upper camel caseDo not use underscores to separate wordsUse the singular form of nouns

E.g.: FirstName, DateOfBirth

Using the data type as a prefix is not considered a best practice anymore

For identity column names use table name suffixed with ‘ID’

Suggestions?

Page 9: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Other SQL Server objects Views: vwSalesSummary2007 Indexes: IX_Customers_SocialSecurityNumber Stored Procedures:

Do not prefix with sp_ Names based on functionality:

Get: GetSalesInvoices Insert: InsertCustomers Update: UpdateCourses

References: http://vyaskn.tripod.com/object_naming.htm http://www.cms.hhs.gov/dbadmin/downloads/sqlserverstandardsandguildelines.

pdf

Object Naming Conventions

Page 10: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Prettifying the Horrifying

Page 11: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

HorrifyingTake a look at this piece of code:

Page 12: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Prettifying the HorrifyingWhy prettify?

Readability by othersReadability by selfResults in:

Ease of debugging and modifying of code

Page 13: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Prettifying the HorrifyingHow to prettify?

IndentsCommentsUpper case for keywordsShortening linesUse square braces for table/view names and column

namesUse table aliases using Use tabs instead white spacesSuggestions?

Page 14: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Standards for Creating Tables

Page 15: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Standards for creating tables

Make sure all tables are in the 3rd Normal formPrimary keys for unique row identificationChoosing a primary key

Natural key vs. Surrogate keyNatural keys have a tendency to changeAn integer identity (surrogate) column is the best suited

[UserID] int IDENTITY(1,1)

Avoid GUID/UNIQUEIDENTIFIER data types for primary keyReference:

http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html

Page 16: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Standards for creating tables

Choose data types with the minimal size as possibleUse Unicode data types only if it is neededMake sure data integrity is applied

Primary keys, Foreign keys, Check, Default and Unique constraints

Keep in mind the 8060 B row size ruleChoose

varchar(max), nvarchar(max) and varbinary(max) over text, ntext and image

Page 17: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Standards for creating tables

Avoid storing BLOBs in tables especially if there is constant accessAlternatively:

Store the path in the table and the data in files Store the data in a varbinary(max) field using FILESTREAM

(SQL Server 2008)

Page 18: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Best Querying Practices

Page 19: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Querying TipsRather than SELECT * FROM …

use SELECT [col1],… [coln] FROM …Select only the columns that are required for output

Use Common Tables Expressions (CTEs) wherever possible instead of temporary and derived tables

SET NOCOUNT ON within batches and stored procedures to increase on performance

Page 20: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Querying TipsAvoid cursors as much as possible

Alternatively use: Set based approach to update or insert data from one tables

to another Tables variable and While loop (suited for small result sets)

Wild card characters at the beginning of a phrase in the LIKE clause should be avoidedWHERE [Name] LIKE ‘%Powell’

Refer to table names with schema name prefixed… FROM [HumanResources].[Employee]

Page 21: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Querying TipsPrefix column names with table name or alias

SELECT Employee.[Name], Contact.[Address]FROM …

Avoid using functions on columns in the WHERE clauseWHERE UPPER([Name]) = ‘BARBIE’

Declare all variables and initialize values at the beginning of the code (Makes the query optimizer reuse plans)

When checking for existence of records, simply useIF EXISTS(SELECT * FROM dbo.Employees).It does not return a result set, hence is fast.

Page 22: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Querying TipsAvoid dynamic SQL

Try to find alternatives that do not constitute of dynamic SQL. If at all using dynamic SQL, use sp_executesql instead of EXECUTE (EXEC)

When testing query performance using the graphical execution plan, look for Index seeks over Index scans or Table scans.

When performing Inserts, use column list in the INSERT clause:INSERT INTO ([Name], [Age], [Address])

VALUES (‘Neil’, 32, ‘Hendala Junc.’)

Page 23: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Querying TipsPlace all data access tasks in SQL Server itself.

Avoid queries and data manipulations on the client app/business tier.Use stored procedures

Reference: http://blog.sqlauthority.com/2008/09/25/sql-server-guideline

s-and-coding-standards/

Suggestions?

Page 24: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Trigger Mania

Page 25: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Trigger Mania

Perform all referential and domain integrity rules using

constraints Avoid using triggers for this purpose (poor performance)

Use only if cannot be implemented by constraints

Avoid triggers for business functionality Less visible

Can avoid indirect recursion problems

Alternatively use stored procedures

Triggers can be used for tasks such as auditing and custom

validations

Page 26: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Trigger Mania

When writing triggers

Write for a recordset rather than for a single record

Suggestions?

Page 27: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Q & A

Page 28: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Q1You have an SQL Server 2008 database. You need to

load data from one table to another. New records will have to be added, existing records need to be updated and records not in the source should be deleted from the destination.

How would you perform this with best performance?Using the MERGE statement

Page 29: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Q2You use an SQL Server 2005 database. You need to

store map images which are between 50MB and 100MB in size. What is the optimum method to perform the storage?Store the images in the file system and the file path in an

SQL Server table

Page 30: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Q3What alternatives can be used for cursors?

Set based operationsTable variables and WHILE loop (for small data sets)

Page 31: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

Q4Name some Best Practices for triggers.

Avoid using business functionality within triggersCode for record sets rather than single recordsBest suited for auditing and other custom tasks

Page 32: Gogula G. Aryalingam T-SQL Coding Standards And Best Practices for developers

E-mail: [email protected]: http://twitter.com/gogulaBlog: http://dbantics.wordpress.comWeb: http://sqlserveruniverse.com

Thank you