Reference database object naming

Reference database object naming

A reference herein is not a specification, but not a standard. It represents only my personal views and suggestions, and consider only the rules under normal conditions, you can freely modify it according to the actual situation.

introduction

Coding standards are essential qualities of a good programmer, however, there are a lot of people very focused program variables, methods, classes named, but they ignore the equally important database object naming. This article combined with many technical articles and information, as well as my own experience in the development of database object naming rules put forward some suggestions, hoping to provide some reference.

NOTE: Although this article titled "Database object naming reference", in fact, in this article I not only introduced the rules database named jointly and severally, describes some problems in database design and development that need attention.

Basic naming rules

Table 1. Basic database object naming

Database Objects Prefix For example
Table (Table)
field (Column)
view (View)
stored procedure (Stored procedure)
flip-flop (the Trigger)
index (Index)
primary key (Primary key)
foreign key (Foreign Key)
the Check constraints (the Check the Constraint)
of Unique constraint
user-defined data types (user-defined data type)
user-defined function (user-defined function)
No
No
v
PR
TR
ix_
PK_
fk_
ck_
uq_
UDT
the Fn
Student
Title
vActivity
prDelOrder
trOrder_D
ix_CustomerID
pk_Admin
fk_Order_OrderType
ck_TableColumn
uq_TableColumn
udtPhone
fnDueDate

Agreed on naming

Variable (T-SQL variables declared in the program), process (stored procedures or triggers, etc.), entities (tables, fields) should be based on the entity significance and role in the process they represent are named:

Table 2. good names and bad examples of names

Good name Bad name
@CurrentDate
@ActivityCount
@EquipmentType
prCalculateTotalPrice
@D
@ActNum
@ET
@prRunCalc

Another common mistake is to use only computer-oriented terms, rather than the term for the company's business, such as ProcessRecord is a vague name, description should replace it with a business process, such as CompleteOrder.

If based solely on a requirement, then according to the procedure described in the business name may become very lengthy, such as the following:

prCountTotalAmountOfMonthlyPayments (calculate the total amount of monthly pay)

prGetParentOrganizationalUnitName (get the name of the parent unit)

At this point you should consider using abbreviations:

  • If you can find an abbreviation of the word in the dictionary, use this as an abbreviation, such as: Mon (Monday), Dec (December)
  • You can delete the word vowel (except for the first letter of the word) and repeats letter of each word to an abbreviation of a word. For example: Current = Crnt, Address = Adr, Error = Err, Average = Avg
  • Do not use abbreviations discrepancy (usually ambiguity on the speech). For example, b4 (before), xqt (execute), 4tran (Fortran)

Tables, fields named:

Singular table names, field names or plural table names, field names?

We may rarely taken into account to the table name from the singular or plural, for example, to store information table guests, we should take the Customer, or Customers? I advocate from the singular table names, the following is from a period of "SQL Server 2000 Collection," a reference to:

Advocate the use of camp complex table names considered: Table is constituted by a set of records, so you should use a plural noun to name it. They often use the grounds that: Customers table is the set of customers, and collection means more, and therefore should call them the Customers table. Unless you have only a client, but this you do not need a database.

According to the author of an informal survey, three-quarters of SQL Server Developer Support singular name. The developers believe that customer table is a collection of customers, rather than the client's collection. A set of rows should not and can not become rows set (the set of their lines), and will be called row set (rowset). And, usually when discussing people will use to refer to the singular name of the table, say the Customer table than to say the Customers table sounds more clearly.

Avoid unnecessary table suffix

These two points I think we all know: 1, tables are used to store data information. 2, the table is a collection of rows. So if the table has been able to explain the data information it contains, you do not need to add suffixes reflect the above two points.

Practice, I saw some of my colleagues on the table so named: GuestInfo, used to store customer information. This name is repeated with the above mentioned point 1, everyone knows that the table was originally stored information (information), plus a superfluous Info tantamount to the individual that do directly with Guest table name on it.

For table stored flight information, he was named FlightList. This in turn is named said before repeating the point 2, the table is a set of rows, so natural is a list (List), plus a suffix made redundant List, named Flight not very good? Here, he himself did not draw up a clear naming convention, or the two tables must be either named: GuestList, FlightList either named GuestInfo, FlightInfo, but not a mix of both.

Many relationship named in connection table

As you know, if you want to achieve-many relationship between two entities, you need three tables, one of which is the resolution table. Consider the following a to-many relationship, this is a classic problem of student enrollment: Students can choose a lot of courses, a course can have a lot of students. At this time, in order to achieve the above relation, we need a resolution table (this table only stores the ID and student ID programs, and student information and course information respectively present their own table), the table is named, the proposed wording is the names of the two tables combined table (comparison table if simplification do long), where such StudentCourse. This table field named StudentId, CourseID (both composite primary key of this table, simultaneously connected Student table and the Course table foreign keys, and the like at the primary and foreign keys named at say), thus achieving a student and many relationships between classes, of course, this relationship can also add a little something extra, such as to StudentCourse table plus AccessLevel field range D {read-only, completely prohibit}, we can achieve the level of access.

Field name before the convention / suffix

Database development for a long time, and slowly worked out a law would be: is that many fields have some common characteristics. For example, some fields are representative of time (such as post time, review time), the number of representatives of some (such as Views, comments), some representatives of true and false type (for example, whether the blog essays appear in the home page). For this same type of field, you should use a unified prefix or suffix to identify it.

We give you a few examples to see a little more clearly.

We are all familiar with the forum, the need to record the time of the last member login, this time most people will put this field named LoginTime or LoginDate. At this time, has produced an ambiguity: For another developer, if we look at the table of the field names only, not to look at the contents of the table, it is easy to understand LoginTime into a number of login, because there is a Time common sense, that is the number.

To prevent this from happening, it should be clearly defined: all fields representing time, unified as a Date as the end.

We often need to statistics posted, Replies information, this time, developers often go so named fields: PostAmount, PostTime, PostCount, Again, due to the Time of ambiguity, we do not rule out first use PostTime as the field name. Next, Amount and Count can count represents the meaning, which is appropriate with it? Here, I recommend using the Count. why? If you did Asp development, I believe we know the RecordCount property, when naming a principle: that is, using the name of the convention without going to create their own name . Since Microsoft have with Count suffix to indicate the number, why do not we do?

So, all numbers represent fields should Count as to the end. Do to promote this concept, it is easy to draw, visits to ViewCount, logins for the LoginCount and so on.

As another example, we rarely stored directly in the database, pictures and other binary data, usually only save the image URL path; in the article management system, if the article is reproduced, the recording will be used Article Source field. Personal recommendations on behalf of all the fields linked, are the end of Url. Thus, the image path field named ImageUrl, naming Article Source field is SourceUrl.

The last example, we often need to use a Boolean value, for example, this essay not to show to the home page, this essay is not saved to the Drafts and so on. Also, according to Microsoft's proposal, boolean values are Is, Has, or the beginning of Can.

If I had to build into the essay indicates whether the home field, its name must be the case: IsOnIndex

Similar examples are many, I am here just to mention a few typical examples, we can expand on their own, if I can play a role in better ideas will be satisfied.

One problem to be aware of when naming fields

I have found many developers prefer to field it with the table name as a prefix, for example, if you have a table called User, then he will be named in this table fields: UserId, UserPassword, UserName, UserPhone etc. Wait. Personally think that this is not necessary, because you already know exactly what this table is stored in the User information, then one of the fields must be directed to the User. Moreover, Join join operation, your SQL code will be more streamlined look of some, such as [User] .UserName = Aritcle.ArticleAuthor Such code can be implemented as [User] .Name = Article.Author.

Here there is also a special case, is the foreign key table included. In this case, I tend to use the table name + mode ID, such as CategoryId, UserId and so on. Suppose table Article, then I will be its primary key named Id, foreign key field containing the user table User, I will name UserId. The reason for this is because when you create an object in the language (such as C #), a sometimes use code generator (field, property name generation target according to the database field name), then the generated code more regular number.

Issues to consider when construction of the table

Not only is the database used to store data, should be responsible for maintaining data integrity and consistency

I've seen a lot of developers designed the database, I feel is this: In their eyes, the role of the database just as its name suggests - is only used to store data, in addition had to build the primary key, Check nothing ... no constraints, no index, no foreign key constraint, no view, not even stored procedures.

Here, I recommend the following database design:

  1. If you want to write code to ensure rows in the table is unique, add a primary key for the table.
  2. If write code to ensure a separate column of the table is unique, add a constraint on the table.
  3. If the value is determined to write the code column of the table can only belong to a certain range, add a Check constraint.
  4. If you want to write code to connect to the parent - child table, you create a relationship.
  5. If you want to write code to maintain "Once a parent row in a table changes, joint-related changes in the child table row" is enabled cascading deletes and updates.
  6. If you want to call a large number of Join to a query, create a view.
  7. If you want to write the statement by one of the database operation to complete a business rule, you use stored procedures.

NOTE: Here I did not mention the flip-flop, flip-flop proved database will quickly become too complex, more important is the trigger difficult to debug, if not carefully built a chain of flip-flops, even a headache, so I prefer simply do not use triggers.

Not Null with the idea to build the table of

I found that when many developers in the construction of the table, if you want to create a new field, his idea is this: By default this field is to Null, and then to judge is not necessarily Not Null can not, if not, OK, this field can be Null, then proceeds to the next field. The result is often a table in addition to all the primary key fields can be thought Null.

The reason why there is such a thought, because Null Well, the program is not easy to make mistakes ah, when you insert the record if you accidentally forget to lose a field, the program can still Run, but does not appear "XX field can not be Null" error message.

However, the result of this is very serious, but also make your program become more complicated, you have to make some unnecessary null handling to avoid procedural errors. Even worse, if some important data, such as a particular value of orders Null, then we all know, any value Null phase operation (such as addition and subtraction, multiplication and division), the result is Null, result is that orders The total amount also Null.

You can try to run the following code:

Select Null + 5 As Result

You might say, even if I set a field to Not Null, but it is still acceptable to the empty string, so that still have to be null processed in the program. Please do not forget, the database also gives you a powerful weapon, is the Check constraint, when you need to make sure neither one field can be Null, nor can is empty, you can write:

ColumnName    Varchar(50)       Not Null Constraint ck_ColumnName Check(Len(ColumnName) > 0)

Therefore, a reasonable way of thinking should be like this: This field is the default Not Null, and then determine whether this is not a non-field is not Null, if not, OK, this field is Not Null, and the next field.

Build a table of the sample script

I'm creating my own personal space in which the table article is written like this:

The Table Article This article was the Create
(
    Id Int the Identity (1, 1) Not Null,
    the Title Varchar (50) Not Null Constraint uq_ArticleTitle of Unique,
    Keywords Varchar (50) Not Null,
    the Abstract Varchar (500) Not Null,
    Author Varchar (50) Not Null the Default 'Zhang Zaiyang',
    the Type 0 TinyInt the Default Null Not the Constraint ck_ArticleType the Check (in the Type (0,1,2)), - 0, the original; 1, compile; 2, translation
    IsOnIndex Bit Not Null Default 1, - whether the Home
    Content Text Not Null,
    SourceCode Varchar (100) Null, - program source code download path
    Source Varchar (50) Not Null Default 'TraceFact', - the article source
    SrcUrl Varchar (150) Null, - URL source of the article is
    postdate the Default GetDate DateTime Not Null (),
    the viewCount Int Not Null the Default 0,
    ClassId Int Not Null - foreign key field contains the article category

    Constraint pk_Article Primary Key (Id) - Create primary key
)

We can see, here I am using the Check constraint, to ensure that the type of article can only be 0,1,2. Here, I want to say is Check Constraints naming rules: Despite Check constraints are for the field, but in the same database, but can not have the same name Check constraints. Therefore, it is recommended to use ck_ + table name + column names to name it, such as this example script ck_ArticleType.

In addition, I also used the Unique constraint to ensure uniqueness of the title of the article. Since this is my blog post table, repeat title should not appear, avoid insert duplicate values ​​when using the Insert statement. Check similar constraints, here naming convention is: uq_ + table name + column names.

Primary key name

(The default name of the primary key generated when you create a primary key using the Enterprise Manager) according to the default specification of SQL Server, naming the primary key for the pk_TableName. Is the primary key for a table, rather than a field, you sometimes Enterprise Manager will see a table in front of two fields will have a key icon (such as EmployeeTerritories table 2000 NorthWind sample database that comes with the SQL Server ), will be mistaken to be the primary key for the field, that is a two primary key, in fact wrong, there is only one primary key, but contains two fields on the table, it is often said that the composite primary key. In order to have a more vivid understanding, look at the establishment of a composite primary key SQL statements to the above mentioned-many join table StudentCourse example:

Alter Table StudentCourse
Add Constraint pk_StudentCourse Primary key(StudentId, CourseId)

It is seen, for a primary key pk_StudentCourse, and contains two fields StudentId CourseId.

Foreign key name

Name the foreign key is fk_ foreign key table name of the table _ name the foreign key references . Because the table where the foreign key from the table, so the above equation can be written as fk_ table _ name from the primary table .

Name field contains a foreign key, foreign key and foreign key fields comprising a completely different concept. Foreign key field contains the name, it is recommended to: foreign key name of the table + Id.

Consider a relationship table Hotel, field Id, Name, CityId. Table City, fields Id, Name. Because the city might have a lot of hotels, so the relationship is one to many, City is the main table (1 side), Hotel from the list (multi-party). Hotel in the table, CityId is as a foreign key.

When implementing foreign key we can write:

Alter Table HotelInfo
Add Constraint fk_HotelInfo_City Foreign Key (CityID) References City(ID)
On Delete No Action On update No Action

Obviously, fk_HotelInfo_City is the name of the foreign key, CityId is the name of the foreign key contains fields.

NOTE: When creating a database table, it normally takes three written SQL script file. The first file contains only SQL statements to create all the tables that Create Table statement. The second file contains statements and delete the relationship table, where all of sentence deleted relations, namely Drop Constraint statement concentrated in the upper part of this document, the statement deletes all tables, Drop Table statement, concentrated in the second half of this document section. The third file contains statements establish relationships between tables. This approach will have a greater convenience when you transplant database, because I will not explain you a try at a glance.

As for the foreign key field contained many relationship parsing table, ko push down, we can write (to return to many to many examples of student enrollment):

Establish a foreign key relationship with the Student resolution table StudentCourse table:

Alter Table StudentCourse
Add Constraint fk_StudentCourse_Student Foreign Key (StudentId) References Student (Id)
On Delete No Action On Update No Action

Establish a foreign key relationship with the resolution table StudentCourse Course table:

Alter Table StudentCourse
Add Constraint fk_StudentCourse_Course Foreign Key (CourseId) References Course(Id)
On Delete No Action On Update No Action

Trigger name

It consists of three parts:

  1. Prefix (tr), describes the type of database object.
  2. The basic portion table described trigger is applied.
  3. Suffix (_I, _U, _D), shows a modification statements (Insert, Update and Delete)

Name of the stored procedure

As you know, the prefix system stored procedure is sp_, to avoid confusing the user with the system stored procedure stored procedure, I recommend that you use the name of the stored procedure as a pr own definition.

Meanwhile, the naming rule is: The type of self-explanatory name, such as: prGetItemById.

Here, there is an interesting place worth considering. We according to the above rules when naming stored procedures can be used in two ways:

  1. Put in front of the verb, noun put back.
  2. Put in front of nouns, verbs put back.

I personally recommend using Mode 2, now we talk about the reasons:

To NorthWind for example, if you have the Employees table for four stored procedures, were named as: prEmployeeInsert, prEmployeeUpdate, prEmployeeDelById, prEmployeeGetById

For the Products table while you have a stored procedure similar to the four were named as: prProductInsert, prProductUpdate, prProductDelById, prProductGetById

Then, when you use Enterprise Manager to view, you will find stored procedure like this neat arrangement:

prEmployeeDelById
prEmployeeGetById
prEmployeeInsert
prEmployeeUpdate
prProductDelById
prProductGetById
prProductInsert
prProductUpdate

It's easy to find you a long time when the stored procedure, named after the more obvious advantages of this approach.

Naming the stored procedure parameters

Entrance parameters stored procedure, I would suggest the same field names with their corresponding, here, it is assumed to write a update stored procedure in the Northwind database Employees table (do simplified), you can write:

Create Procedure prEmployeeUpdateById
    @EmployeeId       Int,
    @LastName     NVarchar(20),
    @FirstName    NVarchar(10)
As
    Update Employees Set
       LastName = @LastName,
       FirstName = @FirstName
    Where
       EmployeeId = @EmployeeId

    If @@error <> 0 or @@RowCount = 0
       Raiserror 16001 ‘更新用户失败’

to sum up

In this article, I first proposed developers of database object naming insufficient attention to the problem, and then lists a data object named profile.

Then I according to tables, fields, primary key, foreign key, triggers, sequentially stored procedure, a detailed account of the rules database named objects.

In the meantime, I also interspersed with covers some common problems in database development, including issues to be aware of when construction of the table, as well as skills in the management of the stored procedure can take.

Hopefully this article will give you help.

Reproduced in: https: //www.cnblogs.com/JimmyZhang/archive/2007/08/30/875504.html

Guess you like

Origin blog.csdn.net/weixin_34217773/article/details/93444008