Wednesday, October 7, 2015

SQL SERVER – Guidelines and Coding Standards Complete List

Guidelines and Coding Standards Part – 2



  • To express apostrophe within a string, nest single quotes (two single quotes).
Example:
SET @sExample 'SQL''s Authority'
    • When working with branch conditions or complicated expressions, use parenthesis to increase readability.
    IF ((SELECT 1FROM TableNameWHERE 1=2ISNULL)
    • To mark single line as comment use (–) before statement. To mark section of code as comment use (/*…*/).
    • If there is no need of resultset then use syntax that doesn’t return a resultset.
    IF EXISTS   (SELECT 1
    FROM UserDetails
    WHERE UserID 50)
        Rather than,
      IF EXISTS  (SELECT COUNT (UserID)
      FROM UserDetails
      WHERE UserID 50)
      • Use graphical execution plan in Query Analyzer or SHOWPLAN_TEXT orSHOWPLAN_ALL commands to analyze SQL queries. Your queries should do an “Index Seek” instead of an “Index Scan” or a “Table Scan”. (Read More Here)
      • Do not prefix stored procedure names with “SP_”, as “SP_” is reserved for system stored procedures.
        Example:
        SP<App Name>_ [<Group Name >_] <Action><table/logical instance>
      • Incorporate your frequently required, complicated joins and calculations into a view so that you don’t have to repeat those joins/calculations in all your queries. Instead, just select from the view. (Read More Here)
      • Do not query / manipulate the data directly in your front end application, instead create stored procedures, and let your applications to access stored procedure.
      • Do not store binary or image files (Binary Large Objects or BLOBs) inside the database. Instead, store the path to the binary or image file in the database and use that as a pointer to the actual file stored on a server.
      • Use the CHAR datatype for a non-nullable column, as it will be the fixed length column, NULL value will also block the defined bytes.
      • Avoid using dynamic SQL statements if you can write T-SQL code without using them.
      • Minimize the use of Nulls. Because they incur more complexity in queries and updates.ISNULL and COALESCE functions are helpful in dealing with NULL values
      • Use Unicode datatypes, like NCHAR, NVARCHAR or NTEXT if it needed, as they use twice as much space as non-Unicode datatypes.
      • Always use column list in INSERT statements of SQL queries. This will avoid problem when table structure changes.
      • Perform all referential integrity checks and data validations using constraintsinstead of triggers, as they are faster. Limit the use of triggers only for auditing, custom tasks, and validations that cannot be performed using constraints.
      • Always access tables in the same order in all stored procedure and triggers consistently. This will avoid deadlocks. (Read More Here)
      • Do not call functions repeatedly in stored procedures, triggers, functions and batches, instead call the function once and store the result in a variable, for later use.
      • With Begin and End Transaction always use global variable @@ERROR, immediately after data manipulation statements (INSERT/UPDATE/DELETE), so that if there is an Error the transaction can be rollback.
      • Excessive usage of GOTO can lead to hard-to-read and understand code.
        • Do not use column numbers in the ORDER BY clause; it will reduce the readability of SQL query.
          Example: Wrong Statement
          SELECT UserIDUserNamePasswordFROM UserDetailsORDER BY 2
        Example: Correct Statement
        SELECT UserIDUserNamePasswordFROM UserDetailsORDER BY UserName
        • The RETURN statement is meant for returning the execution status only, but not data. If you need to return data, use OUTPUT parameters.
        • If stored procedure always returns single row resultset, then consider returning the resultset using OUTPUT parameters instead of SELECT statement, as ADO handles OUTPUT parameters faster than resultsets returned by SELECT statements.
        • Effective indexes are one of the best ways to improve performance in a database application.
        • BULK INSERT command helps to import a data file into a database table or view in a user‐specified format.
        • Use Policy Management to make or define and enforce your own policies fro configuring and managing SQL Server across the enterprise, eg. Policy that Prefixes for stored procedures should be sp.
        • Use sparse columns to reduce the space requirements for null values. (Read More Here)
        • Use MERGE Statement to implement multiple DML operations instead of writing separate INSERT, UPDATE, DELETE statements.
        • When some particular records are retrieved frequently, apply Filtered Index to improve query performace, faster retrieval and reduce index maintenance costs.
        • EXCEPT or NOT EXIST clause can be used in place of LEFT JOIN or NOT IN for better peformance.
        Example:
        SELECT EmpNoEmpName
        FROM EmployeeRecord
        WHERE Salary 1000 AND Salary
        NOT IN (SELECT Salary
        FROM EmployeeRecord
        WHERE Salary 2000);
            (Recomended)
          SELECT EmpNoEmpNameFROM EmployeeRecordWHERE Salery 1000EXCEPT
          SELECT 
          EmpNoEmpNameFROM EmployeeRecordWHERE Salery 2000ORDER BY EmpName;

          Reference : Pinal Dave (http://blog.SQLAuthority.com)

          No comments:

          Post a Comment