SQL Server Coding Standards: Hexaware Technologies
SQL Server Coding Standards: Hexaware Technologies
Hexaware Technologies
All rights reserved. All text and figures included in the manual are the exclusive property of Hexaware
Technologies, and may not be copied, reproduced, or used in any way without the express permission in writing of
Hexaware Technologies.
SQL Server Coding Standards
Version 1.0
1.0
1.1
2
SQL Server Coding Standards
Version 1.0
Table of Contents
1. INTRODUCTION .............................................................................................4
2 NAMING STYLES..............................................................................................4
2.1.1 Pascal Casing .........................................................................................................4
2.1.2 Camel Casing..........................................................................................................4
2.1.3 Upper Case..............................................................................................................4
3 NAMING..........................................................................................................5
3.1 TABLE NAMING STYLES............................................................................................................5
3.2 STORED PROCEDURE...............................................................................................................5
3.3 USER DEFINED FUNCTION........................................................................................................10
3.4 TRIGGER...........................................................................................................................10
3.5 INDEX..............................................................................................................................11
3.6 VIEWS.............................................................................................................................11
3.7 COLUMN...........................................................................................................................12
3.8 USER DEFINED DATA TYPE.....................................................................................................12
3.9 PRIMARY KEY.....................................................................................................................12
3.10 FOREIGN KEY..................................................................................................................13
4 CODING ........................................................................................................13
5 FORMATTING.................................................................................................16
6 GENERAL.......................................................................................................17
7 EXCEPTION HANDLING...................................................................................18
3
SQL Server Coding Standards
Version 1.0
1. Introduction
2 Naming Styles
4
SQL Server Coding Standards
Version 1.0
3 Naming
3.1 Table Naming Styles
Prefix table name with Project name and TBL keyword and suffix with the
type of table.
Rule: TBL_TABLENAME1_TABLENAME2_DTL
Example: AMS_ TBL_CUSTOMER_ADDRESS_DTL
If the table is for audit trail purpose add _LOG at the end of the table name.
Rule: TBL_TABLENAME_LOG
Example: AMS_TBL_FIXEDASSETADDITION_LOG
Rule: PROJECT_SP_STOREDPROCEDURENAME
Example: AMS_SP_GETCUSTOMERDETAILS
/*
***********************************************************************************************
5
SQL Server Coding Standards
Version 1.0
** SP Name : BANK_SP_MONTHWISEBALANCE **
** Created By : xxxxxx **
** Date : dd-mm-yyy **
** Inputs : LedgerId As Int **
** CompanyId As Int **
** FinancialYear As Varchar(7) **
** FromDate As DateTime **
** ToDate As DateTime **
NOTE: This stored proc returns a table with all the month names. The First
record alone will be the Opening Balance. Other records mention the Month
Name.
*/
Return multiple result sets from one stored procedure to avoid trips
from the application server to SQL server.
6
SQL Server Coding Standards
Version 1.0
Place all DECLARE statements before any other code in the procedure.
Example:
Example:
Example:
7
SQL Server Coding Standards
Version 1.0
Begin
return 1
End
For example
Do not prefix stored procedure names with 'sp_'. The prefix sp_ is
reserved for system stored procedure that ship with SQL Server. Whenever
SQL Server encounters a procedure name starting with sp_,, it first tries to
locate the procedure in the master database, then looks for any qualifiers
(database, owner) provided, then using dbo as the owner. This can really
save time in locating the stored procedure by avoiding sp_ prefix. But there is
an exception! While creating general purpose stored procedures that are
called from all your databases go ahead and prefix those stored procedure
names with sp_ and create them in the master database.
8
SQL Server Coding Standards
Version 1.0
9
SQL Server Coding Standards
Version 1.0
Rule: PROJECT_FN_FUNCTIONNAME
Example: BANK_FN_GETLASTDAYOFMONTH
Example:
3.4 Trigger
Prefix Triggers with the Project name and the keyword TRG.
Rule: PROJECT_TRG_TABLENAME_<’_’Separated
Actionnames>_TriggerName
Example: AMS_TRG_CUSTOMER_INS_VALIDATECUSTOMER
10
SQL Server Coding Standards
Version 1.0
3.5 Index
Prefix Index with Project name and Index Type and suffix with the Column
on which the index has to be set.
All Queries should do 'Index seeks' instead of 'Index scans' or 'Table scans'.
3.6 Views
Prefix Views with Project name and keyword VW
Rule: PROJECT_VW_TABLENAME
Example: AMS_VW_CUSTOMER
Views are also used to restrict access to the base tables by granting
permission on only views.
11
SQL Server Coding Standards
Version 1.0
3.7 Column
Prefix Column with Project name and Table Name and suffix with Data Type.
Rule: PROJECT_TBL_COLUMNNAME_DATATYPE
Example: AMS_CUST_CODE_INT
Rule:PROJECT_UDT_DATABASENAME_TYPENAME_BASEDATATYPE
Example: AMS_UDT_MDL_SSN_VCH
- UDT Created in Model DB
- Type Name = SSN of Varchar Datatype
Rule: PROJECT_PK_TABLENAME_COLUMNNAME
Example: AMS_PK_CUST_CODE
12
SQL Server Coding Standards
Version 1.0
Rule: PROJECT_FK_TABLENAME_COLUMNNAME
Example: AMS_FK_CUST_DEPT
Foreign key is a column or set of columns in one table that refer to the
primary key of another table.
The reference from the foreign key to the primary key is the mechanism
whereby the relationships between the occurrences of rows in the two
tables are enforced.
The table containing the foreign key is referred to as the child, and the
table containing the referenced key is the parent table.
The foreign key and referenced key can be in the same table (parent
and child are the same table); otherwise, the parent and child tables must be
in the same database.
4 Coding
Do not use SELECT *. Always write the required column names after
the SELECT statement, like SELECT CustomerID, CustomerFirstName, City.
This technique results in less disk IO and less network traffic and hence better
performance.
Try to avoid server side cursors as much as possible. Cursors can be
easily avoided by SELECT statements in many cases. If a cursor is
unavoidable, use a simpleWHILE loop instead, to loop through the table.
Use 'Derived tables' wherever possible, as they perform better.
Consider the following query to find the second highest salary from
Employees table.
13
SQL Server Coding Standards
Version 1.0
SELECT MIN(Salary)
FROM Employees
WHERE EmpID IN
(
SELECT TOP 2 EmpID
FROM Employees
ORDER BY Salary Desc
)
The same query can be re-written using a derived table as shown below, and
it performs twice as fast as the above query
SELECT MIN(Salary)
FROM
(
SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary Desc
) AS A
Use the more readable ANSI-Standard Join clauses instead of the old
style joins. With ANSI joins the WHERE clause is used only for filtering data.
Where as with older style joins, the WHERE clause handles both the join
condition and filtering data. The first of the following two queries shows an
old style join, while the second one shows the new ANSI join syntax.
14
SQL Server Coding Standards
Version 1.0
UPDATE [Link]
SET OrderStatus = @ORDER_PENDING
WHERE OrdDate < '2001/10/25'
Example:
SELECT OrderID, OrderDate
FROM Orders
ORDER BY 2
15
SQL Server Coding Standards
Version 1.0
5 Formatting
Use upper case for all SQL keywords
SELECT, INSERT, UPDATE, WHERE, AND, OR, LIKE, etc.
Example
16
SQL Server Coding Standards
Version 1.0
Use proper commenting. Also add the purpose, author, date, version
etc. details on top of all the procedures, functions etc.
Add test data with statements inside stored procedures and comment
it. This helps you in future debugging. Also this helps another developer to
get a quick start.
Example:
--Exec dbo.TRI_ProfitLoss 5,'2004-05',0,0,0,0,0,0,0,0,0,0
--Exec TRI_MonthwiseBalance 261,25,'2004-05','04/1/2004','11/30/2004',0,0,0,0
6 General
Divide your large table to small multiple tables. (In SQL terminology it
is called as Normalization).
Use the right data types and widths when defining columns.
Example:
To store the 'age', then no need to use the VARCHAR field since a TINYINT
can do the job. (TINYINT can store integer data from 0 to 255 as the fact
that 'age' value does not exceeds 255).
Use stored procedures and functions instead of writing all the messy
code in the program itself. It not only improves the performance but also a
matter of security.
Avoid using CURSORs. Use only when there is no other way exists. In
most cases CURSOR consumes much time since it is a record-by-record
process.
17
SQL Server Coding Standards
Version 1.0
Use the lookup tables. This will help reduce the overload of tables.
Example:
Always try to keep one error table to log all the errors which comes
from the stored procedures or functions. In T-SQL (version < 2000) the global
variable @@ERROR can be used to detect errors. From 2005 or greater
versions TRY/CATCH is available. Its time saving and helps in finding the error
easily.
7 Exception Handling
TRY/CATCH block whenever you use an explicit transaction and whenever
you modify data. Some practitioners advocate using TRY/CATCH blocks in
every stored procedure in order to log any exception that occurs in the
database.
Example:
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
SELECT 'Error Caught'
SELECT
ERROR_MESSAGE(),
ERROR_NUMBER()
END CATCH
BEGIN TRY
BEGIN TRANSACTION
INSERT Funds VALUES (10)
INSERT Funds VALUES (-1)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK
18
SQL Server Coding Standards
Version 1.0
END CATCH
19
SQL Server Coding Standards
Version 1.0
20
SQL Server Coding Standards
Version 1.0
21
SQL Server Coding Standards
Version 1.0
22