Indentation
Properly Indenting your query makes it so much easier to read and / or troubleshoot.
For example, consider the following query..
SELECT FirstName,LastName,EmailAddress,Address1,Address2,Phone,Fax FROM Customers
Can be rewritten as...
SELECT
FirstName,
LastName,
EmailAddress,
Address1,
Address2,
Phone,
Fax
FROM Customers
It is certainly easier to read and you can quickly figure out what columns are being selected. You can make it even more useful by making the following change...
SELECT
FirstName
,LastName
,EmailAddress
,Address1
,Address2
,Phone
,Fax
FROM Customers
By using "," as a prefix in subsequent columns, you can easily comment out a line containing the column that you don't want your query to return instead of having to rearrange it.
Using Square Brackets
Although square brackets are not necessary unless you have a space in column name, using it ensures that if your column name ever becomes a reserved word in SQL, you query won't break. For example, you can write the above query as follows...
SELECT
[FirstName]
,[LastName]
,[EmailAddress]
,[Address1]
,[Address2]
,[Phone]
,[Fax]
FROM [Customers]
Using Statement Terminators
Using semicolon (;) at the end of your SQL Statement. If you use C# or C++ or Java for application development, this may be second nature, but not so much for VB Developers. Although SQL Server currently doesn't require semicolon in most cases, it may change in the future as it is part of the ANSI SQL-92 standard. So to avoid future headaches, always use semicolon. Thus the proper way to write the above query would be...
SELECT
[FirstName]
,[LastName]
,[EmailAddress]
,[Address1]
,[Address2]
,[Phone]
,[Fax]
FROM [Customers];
If you have multiple statements in your query, use semicolon after each one. For example, I can add SET NOCOUNT ON in my query above.
SET NOCOUNT ON;
SELECT
[FirstName]
,[LastName]
,[EmailAddress]
,[Address1]
,[Address2]
,[Phone]
,[Fax]
FROM [Customers];
Capitalize all T-SQL Keywords
Capitalizing T-SQL Keywords such as SELECT, FROM, WHERE, JOIN etc. makes it so much easier to read your query and to differentiate between the T-SQL keywords and your own columns etc.
Happy Programming!
No comments:
Post a Comment
As always, your comments are welcome and appreciated!