Compartilhar via


SQL 2005 - Coding Standards - Basic Formatting and Indentation Rules

Basic Formatting and Indentation

Use 4 spaces for indenting

Use 4 spaces for indenting in your database source files and remain consistent throughout the file on the number of space chosen for an indent.

Editors will allow you to configure the tab key for 4 spaces (as opposed to the default of 8).

Do not use the tab character.

There should be no tab characters in a text source file.

Most editors, aside from Notepad but including Query Analyzer, will allow you to configure your tab key to insert spaces instead of the tab character. This approach will promote consistency with source files across projects, and will ensure documents look good when printed or when they are brought into Query Analyzer.

Line Width

Keep code within 87 characters

The width of code should be kept within 87 characters or as close as possible. If the code is too wide, it has to be scrolled and when printed it will wrap and be not as readable.

Commas

Many of us prefer commas on the left for lists because it is easy to add on new columns without having to add a comma to the last column. Also, it is easy to see if a comma is missing.

Indent a line with a comma by one less character than the normal indent. This keeps the first and subsequent lines in line.

Eg.

DECLARE

    @authorID int

   ,@authorName nvarchar(max)

Brackets

  • A bracket should always appear on its own on a new line
  • Brackets should not be indented from a preceeding line
  • All items within a bracket should be indented – including a bracket

Eg.

WHERE

    (

        t2.[Col4] = 3

        OR

        (

                t2.[Col3] < 6

            AND t2.[Col4] > 5

        )

    )

    AND NOT EXISTS

    (

        SELECT

            *

        FROM

            [dbo].[Table5] t5

        WHERE

            t5.[Col2] = t1.[Col2]

    )

BEGIN, END

  • A BEGIN and END should always appear on its own on a new line
  • BEGIN and END should not be indented from a preceeding line
  • All items within a BEGIN and END should be indented – including a nested BEGIN and END

· When there are a lot of lines between the BEGIN and END it is helpful to comment the END so it can be matched up with the BEGIN more easily.

Eg.

IF EXISTS(SELECT * FROM #table)

BEGIN

   --do something

END

ELSE

BEGIN

   --do something else

END