Overview
This article gives you information on T-SQL coding guidelines.
Use upper case for all SQL keywords e.g. SELECT, INSERT, UPDATE etc. This way it’s going to be very easy to read the SQL Queries. Look at the below example where the keywords like SELECT, FROM are in UPPER case.
Before:
Select * from [dbo].[employee]
After:
SELECT * FROM [dbo].[employee]
Single-line comment markers (--) should be used to comment single line. This approach is basically if we want to write some simple description about variables or functionality then one can use single-line comments.
CREATE TABLE Employee -- A table named Employee ( EMPID INT PRIMARY KEY, -- with Primary Key as EMPId EName VARCHAR (50) NOT NULL, Address VARCHAR (40) NOT NULL, Phone INT )
The above code creates the Employee table. The text after -- in each line is commented out and will not be executed by the SQL Server. This is the preferred approach if you want to comment a single line. Its going to be very painful if you have 100 lines to comment.
Multi-line comments markers (/* */) should be used to comment multiple lines. If you want to provide detailed level description around the objects then this is the preferred approach.
CREATE TABLE Employee /* A table named Employee with Primary Key as EMPId will be created */ ( EMPID INT PRIMARY KEY, -- with Primary Key as EMPId EName VARCHAR (50) NOT NULL, Address VARCHAR (40) NOT NULL, Phone INT )
The above code creates the Employee table. The lines of text after "/*" and before the "*/" are comments and will not be executed by the SQL Server.
Use single quote characters to delimit strings.
There is a big confusion on storing string values in variables - whether to use single quotes or double quotes. Look at the example where we show the string is delimited by single quotes.
a = 'This is a string delimited by single quotes.'
Code should be properly intended to improve readability.
Code indentation is one of the key factors in understanding the whole flow of logic. If it's not properly aligned then it would be very difficult to understand it. Look at the below examples - without code indentation and with code indentation.
Before Code Indentation:
USE pubs IF EXISTS (SELECT name FROM sysobjects WHERE name = author _info' AND type = 'P') DROP PROCEDURE author _info GO USE pubs GO CREATE PROCEDURE author_info AS SELECT a.au_lname, a.au_fname, ta.title, ta.pub_name FROM authors a, titleauthor ta WHERE a.au_id = ta.au_id GO
After Code Indentation:
USE pubs IF EXISTS (SELECT name FROM sysobjects WHERE name = author _info' AND type = 'P') DROP PROCEDURE author _info GO USE pubs GO CREATE PROCEDURE author_info AS SELECT a.au_lname, a.au_fname, ta.title, ta.pub_name FROM authors a, titleauthor ta WHERE a.au_id = ta.au_id GO
You can clearly see the difference between the above code snippets.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|