SQL SERVER Programming Standards
SQL SERVER Programming Standards
Table of contents
1 INTRODUCTION.1
1.1 Description. ....................................................................................................1
1.2 Objective of the Standardss .............................................................................1
1.3 Responsible Person....................................................................................1
2 DATABASE.3
2.1 General Policies..........................................................3
2.1.1 Step From Development to Production...............................................................3
2.2 Test the database objects...............................................................5
2.3 Programming recommendations ..............................................................5
3 DATABASE DESIGN.6
3.1 General Information
3.2 Rules for Naming Tables ..........................................................................8
3.3 Rules for Naming Fields........................................................................9
3.4 Rules for Naming Stored Proceduress ....................................10
3.5 Rules for Naming Functions......................................................11
3.6 Rules for naming Trigger. .......................................................................12
3.7 Rules for naming Jobs............................................................................12
3.8 Rules for naming VIEWS. .
3.9 Format for documenting objects. ...............................................................13
4 RECOMMENDATIONS
4.1 TIP for programming in T-SQL
4.1.1 Lecturea ................................................................17
4.1.2 Joins
4.1.3 Where ......................................................................................................18
4.1.4 General ................................................................................................19
4.1.5 Transactionalityd....................................................................................19
1 Introduction
1.1 Description.
The present standards manual includes the technical standards.
applicable to logical design, physical design, and construction of the database and system
security under the Microsoft SQL environment and development tools
Microsoft Visual Studio.
The content of the manual must evolve in accordance with the needs of
application development, the level of implementation of development methodologies and
the practice itself, which is why its main purpose is to serve as the framework document that
At all times, collect the norms that are considered updated.
applicable.
Database Administrator
Physical Design of the Database
Index
Clusters
Database
Analyst
Logical Database Design
Tables
Fields
Table restriction
Views
Materialized Views
Sequences
Security Systems
Users
Groups and Hierarchies
Privileges
Audit
Programmer
T-SQL Language
ASP-NET Language
Report Services
2 Databases
The DBA or responsible person will review compliance with the characteristics.
what each object (defined in the document) should have, for example
name format, primary keys, relationships between tables, types of
data, among others.
The production deployment should be done in the early hours of the day, from
Monday to Friday from 8 am to 3 pm at the latest, for the purpose of
ensure the presence of the system analyst in case there is a
incident.
Example:
There are cases where a query is made to the same table within the
SELECT
SELECT column1, (SELECT column5 FROM Table1 WHERE
column9=522) as column5, column6 FROM Table1 column9=522
it is advisable to use a LEFT JOIN.
For the use of temporary tables, the amount of data that it should hold
it should not exceed 5000 records, because this object makes use
exclusively from memory.
3 Database Design
3.1 Generalities
Nomenclature:
Object Type
Example:
Example:
tb_ges_daily_balance
Example:
The table of 'Customer Transactions' would be called the
next form:
tb_clientTransaction
Example:
tb_customer_address
idea
Object Type Description
Object
Destination table, whose source is originated
Td SQL Table
from an external data source (ETL)
Base configuration or master table
Tb SQL Table
internal features of the application
Grouping table, originated as a
You SQL Table summary of one or more destination tables, for
to optimize the issuance of reports.
Temporary table, used to store
temporarily the data in a
Tt SQL Table processing or generating reports,
the content can be deleted in
cleaning process.
Intermediate table, image of a table
external source, used to speed up the
You SQL Table
load and use stored procedures
you transform the data in the ETL process
Tk SQL Table Backup Tables
Pk SQL Index Primary index
Ak SQL Index Alternate index
Scope of
Description
Business
ges Management
gen General procedures and functions
seg Security
tar ETL execution tasks
Systems for the use of documentation and procedure
sis general development utilities or
maintenance.
ren Profitability
with Monitoring of compliance indicators
crab Management notebook
pre Budget system (bifopres)
spr Proposal follow-up
Any other business area must be registered in
*
the table of tb_seg_aplicacion
The key fields must be located at the beginning of the table definition
(they must be the first).
The fields are open and it should be as explicit as possible, use dashes
to separate words and not exceed 32 characters, do not use characters
specials like accented words, eñe or symbols, the names must
to be in singular.
There are prefixes that summarize the first word of the field, they are 3 characters long.
what indicates the function of the field and the other characters that express the detail,
always written in lowercase, this standard must prevail since the
it will be used in the development environment and will help reduce time
in the monitoring control.
Prefix Description
can Amount
cod Code
of the Description
directory Address
is State
fec Date
grp Group
idea Identifier
imp Amount
name Name
num Number
for Percentage
tip Type
tot Total
var Variation
Customer code.
Customer address.
The name of the stored procedure must indicate with the identifier of
up procedure.
The name of the stored procedure must indicate the business scope to
Which procedure is being affected.
The name of the stored procedure should indicate the action that it is going to
generate, the permitted actions are as follows:
Example:
The table is called tb_gen_balanza and we are going to create the SP for the record.
the name of the SP will be: up_gen_upd _balanza
Example:
They ask us to visualize debtor clients, and the clients table is called
td_customer, the SP should be called up_ges_sel_debtorCustomers.
Example:
They ask us to visualize indebted clients and how many invoices were issued, the SP
it should be named up_ges_sel_deudaCantidadFactura.
The number of columns to return from a stored procedure must be less than or equal to 32.
columns.
Example: up_ges_sel_debtInvoiceAmount.
You must identify the business field where the function will be used, if
it is a general function, using the 'gen' scope.
Action Description
salt Show a list of the
data.
Used for functions
SQL Table-Value Type
cal Returns a result of
an operation.
Table 004: Actions for the Functions
The name of the function must start with the prefix "fn" in lowercase,
followed by a hyphen, the action to be generated is added (previous box)
and then a name is added that will describe the event in more detail
And it must start with a capital letter.
Example:
In the name of a Trigger, the action in which it will be executed must be indicated.
the permitted actions are the following:
Action Description
ins It will be executed when an INSERT is performed.
upd It will be executed when an UPDATE is performed.
It will be executed when a DELETE is performed.
cud It will be executed when an insert, update or
delete.
The name of the Trigger must start with the prefix 'tr' in lowercase,
followed by a dash, then the identifier of the business area (the
same as used in the table), followed by a hyphen, then the action that
finally perform and the name of the table (without the business prefix).
Example:
It is necessary to create the trigger for the table tb_vta_factura when himself
delete the data, the name must be: tr_vta_del_factura.
The name of a JOBS must start with the prefix "jb", followed by a
script, and then add the affected application code and finally
A name that briefly describes its objective.
Example:
It is necessary to create the jobs to delete the null records from the table
tb_vta_invoice, the name could be:
jb_ removeNullRecordFact.
The name of a view must start with the prefix 'vw' in lowercase.
followed by a hyphen, then the name of the business sector, and
finally the name that briefly describes the objective of
same, remember that they must be in singular.
Example:
Example: vw_ges_clienteVinculado
The format to follow is the following, and must be after the word
of the Object.
-- =============================================
-- Author: jmieses
Create date: 06/02/2012
Update the Application master
-- Updates: 06/02/2013 fcossio @001 I add the field
-- application_tip
-- =============================================
-- START @001
SELECT * FROM tt_test_trial
-- FINAL @001
4 Recommendations
The optimization of the programs depends on who develops the module and must
rely on the statement 'SET EXPLAIN' to see the execution plan of the queries.
When there is a need to completely delete all the content of a table, one
It is recommended to use the TRUNCATE TABLE command for these cases.
The command "DELETE FROM tablename" should not be used because it makes a
sequential traversal of the table to delete it.
Integer vs. Smallint. Advantage: Storage size and maximum range. In the case
The Integer has greater storage because it is 4 bytes while the smallint only
it is 2 bytes.
Decimal vs Float. Advantages: Decimal is a proprietary data type of the engine, the
Arithmetic operations with this type are first processed by the engine, then passed to the
processor, while operations with a float, integer, and smallint are performed
directly the processor, however the advantage of Decimal is the length in the
decimals, that is, it already performs the rounding function when storing, which is why it is more
used.
Transactions. Advantages: Integrity and consistency of the data, the server guarantees
that the operations carried out within the limits of the transaction are complete
on the disk, or in case of a failure during its execution, the database is
will restore to the point before the execution of the transaction. The time that is
keep the record updated within the transaction must be minimal and thus achieve
greater concurrency and availability. Consistent replication. Not using: When the occurrence of a
interruption of a data update, it cannot be ensured how much of the operation
It was carried out, even in a single record operation, it is not possible to know if the data
it was updated on the disk correctly, or if the involved indices were updated
correctly. There is even the possibility of leaving the pages of the disk
inconsistent. In a replicated environment it is not guaranteed that the secondary server
reflect the changes made on the main server. In read-only processes, no
to use transactions.
TODO query must access the tables using indexes (unless the SQL decides not to)
use them). This implies that EVERY table, including temporary ones, must have an Index
Clustered. Optionally, one or more Non-Clustered indexes can be placed.
Example
Do not use: WHERE CONVERT(VARCHAR(10), fec_poliza, 121) = '20051201'
Use: WHERE fec_poliza = CONVERT(DATETIME, "20051201", 121)
In the WHERE clause, never use operators with columns from a table. The
Operators should be placed over the constant with which it will be compared.
Example
Do not use: WHERE num_poliza + 600 = @variable_poliza
Use: WHERE num_poliza = @variable_poliza - 600
All temporary tables must be deleted, there should be no tables with tt_ in the databases.
Production Data.
Each Stored Procedure must include in the header the author's name, the date, and a
brief description of the objective of the SP.
Example:
DELETE FROM td_ges_direccion WHERE cod_direccion IN (#1, #2, #3,..#N)
Instead of this, place the values in a table in such a way that it can be done.
crosses with other tables, such as for
Example:
DELETE td_ges_direccion
FROM DIRECTIONS, #tt_ges_temporal
WHERE td_ges_direccion.cod_address =
tt_ges_temporal.address_code
4.1.1 Reading
Avoid using SELECT *. Always read only the columns you need. With this
You avoid taking a lot of unnecessary data to the client, so it
it decongests the network and the client feels that it is faster.
For queries of record lists, use the TOP n operator. With this
we avoid bringing many records to the client. The network is also unclogged
and the customer feels that it is faster.
If you use the UNION operator and you are sure that both Queries DO NOT have
duplicate records, so it's better to use UNION ALL, to avoid that
implicitly the DISTINCT operator is used.
Avoid using SELECT ... INTO table_name. This will block system tables.
Instead of this, first create the tables and then rewrite the statement.
like INSERT INTO table_name SELECT ...
If you are going to read data from a single table, avoid doing so using views that use
other tables.
4.1.2 Joins
Write Joins in ANSI format (use the JOIN .. ON clause). This ensures you
to write down all the restrictions without the possibility of forgetting any restriction.
Avoid using the same table more than once in a single query. To improve this, use
temporary tables.
Use
SELECT member_number, first_name, last_name, room_number
FROM members m
INNER JOIN rooms r
ON m.room_number = r.room_number
Instead of using a statement with many Joins where the involved tables are
great, better create a temporary table with the data from the main table (codes)
and then update this table by joining with the secondary tables.
SELECT publisher_name
FROM tb_gen_publisher
WHERE cod_publisher IN
(SELECT cod_publisher FROM tb_gen_title)
Use:
SELECT publisher_name
FROM tb_gen_publisher
INNER JOIN tb_gen_title
ON tb_gen_title.cod_publisher = tb_gen_publisher.cod_publisher
4.1.3 Where
Usa:
If you use LIKE in the WHERE clause, try to use at least 3 characters.
forward as "abc%"
If you use LIKE in the WHERE clause, avoid using the % operator at the beginning: "%abc"
USA
SELECT customer_number, customer_name
FROM customer
WHERE customer_number BETWEEN 1000 and 1004
Avoid using the operators OR, NOT IN, NOT BETWEEN, <>, NOT EXISTS, NOT
LIKE, LIKE '%ABC'
If a query has one or more OR operators, consider rewriting the query in several.
Queries and combine the results using the UNION operator. Remember to use
UNION ALL, if possible.
4.1.4 General
Avoid using cursors. Instead, use temporary tables with an integer field.
identity(1,1) which you can sweep sequentially. Don't forget to index the field.
identity.
Consider that the MIN and MAX functions can use indexes. If possible, create
indexes on the columns on which these functions are used.
When using temporary tables, consider creating indexes for better performance.
performance of your Queries.
Review each query of a stored procedure to ensure that it does not perform a 'table scan'.
(non-indexed search). To study this, activate the "Show Query Plan" directive in
the "Query Analyzer".
Try to ensure that each query uses an index on a column that has a high
dispersion.
Use derived tables whenever possible instead of temporary tables. This is more
reasonable if the information you would store in the temporary table is going to be used
Once. But if you plan to use this data many times within a stored procedure.
Procedure, then it's better a temporary table.
4.1.5 Transactionality
Make sure your transactions are small, meaning they access the least.
number of pages in the database.
Avoid declaring a single large transaction for batch processes. It's better to have
various small transactions and handle reprocesses.