最有用的数据库标准有哪些?

发布于 2024-07-23 10:10:21 字数 249 浏览 7 评论 0原文

我有一些想法,有些是我随着时间的推移积累的,但我真的想知道在建模数据库时是什么让事情顺利进行:

  1. 表名称与主键名称和描述键匹配
  2. 模式按功能区域划分
  3. 尽可能避免复合主键(使用唯一约束)
  4. Camel Case 表名和字段名
  5. 不要在表前添加 tbl_ 前缀,或在 procs 前添加 SP_(无匈牙利表示法)
  6. OLTP 数据库至少应为 BCNF / 4NF

I have some ideas, some that I have accumulated over time, but I really want to know what makes things go smoothly for you when modeling database:

  1. Table name matches Primary Key name and description key
  2. Schemas are by functional area
  3. Avoid composite primary keys where possible (use unique constraints)
  4. Camel Case table names and field names
  5. Do not prefix tables with tbl_, or procs with SP_ (no hungarian notation)
  6. OLTP databases should be atleast in BCNF / 4NF

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

新雨望断虹 2024-07-30 10:10:22

我还没有看到提到的一件事:

永远不要使用数据库关键字作为对象名称。 您不希望每次使用它们时都必须对其进行限定。

如果在创建某些内容时拼写错误,请在发现后立即修复。 不必花费数年时间来记住此表中的 UserName 实际上是 Usernmae。 当没有太多针对它编写的代码时,修复起来会容易得多。

切勿使用隐式连接(逗号语法),始终指定连接。

One thing I haven't seen mentioned yet:

Never use database keywords as object names. You do not want to have to qualify them every time you use them

If you misspell something when you create it, fix it as soon as you notice it. Don't spend years having to remember that in this table UserName is really Usernmae. It's a whole lot easier to fix when there isn't much code written against it.

Never use implied joins (the comma syntax), always specify the joins.

蓝色星空 2024-07-30 10:10:22

将每个人的意见汇总到一个列表中。

命名标准

  • 架构按功能区域(产品、订单、运输)命名
  • 无匈牙利表示法:对象名称中无类型名称(无 strFirstName)
  • 不要使用注册关键字对于对象名称
  • 对象名称中不能有空格或任何特殊字符(仅允许使用字母数字 + 下划线)
  • 以自然方式命名对象(FirstName 而不是 NameFirst)
  • 表名称应与主键名称匹配和描述字段(SalesType – SalesTypeId、SalesTypeDescription)
  • 不要以 tbl_ 或 sp_ 作为前缀
  • 按对象名称命名代码(CustomerSearch、CustomerGetBalance)
  • CamelCase 数据库对象名称
  • 列名称应为单数
    >
  • 表名称可以是复数
  • 为所有约束指定业务名称 (MustEnterFirstName)

数据类型

  • 跨表使用相同的变量类型(邮政编码 - 一个表中为数字,而另一个不是一个好主意)
  • 使用 nNVarChar 来获取客户信息(姓名、地址)等。你永远不知道什么时候你可能会走向跨国公司

在代码中

  • 关键字总是大写
  • 切勿使用隐式连接(逗号语法) - 始终使用显式 INNER JOIN / OUTER JOIN
  • 每行一个 JOIN
  • 每行一个 WHERE 子句
  • 无循环 - 用基于集合的逻辑替换
    >
  • 使用缩写形式的表名作为别名,而不是 A、B、C
  • 避免触发器,除非没有追索权
  • 避免像瘟疫一样使用游标(请阅读 http://www.sqlservercentral.com/articles/T-SQL/66097/)

文档

  • 创建数据库图表
  • 创建数据字典

规范化和引用完整性

  • 尽可能使用单列主键。 在需要时使用唯一约束。
  • 始终强制执行参照完整性
  • 避免 ON DELETE CASCADE
  • OLTP 必须至少为 4NF
  • 每个一对多关系评估为潜在的多对多关系关系
  • 非用户生成的主键
  • 构建基于插入的模型而不是基于更新的
  • PK 到 FK 必须具有相同的名称(Employee.EmployeeId 与 EmployeeSalary.EmployeeId 的字段相同)
  • 除非有双重连接(Person.PersonId 连接到 PersonRelation.PersonId_Parent 和 PersonRelation.PersonId_Child)

维护:运行定期脚本来查找

  • 没有表的模式
  • 孤立的记录
  • 没有表的表主键
  • 没有索引的表
  • 非确定性UDF
  • 备份、备份、备份

做好

  • 保持一致
  • 立即修复错误 /em>
  • 阅读 Joe Celko 的 SQL 编程风格 (ISBN 978-0120887972)

Putting everybody's input together into one list.

Naming Standards

  • Schemas are named by functional area (Products, Orders, Shipping)
  • No Hungarian Notation: No type names in object names (no strFirstName)
  • Do not use registered keywords for object names
  • No spaces or any special characters in object names (Alphanumber + Underscore are the only things allowed)
  • Name objects in a natural way (FirstName instead of NameFirst)
  • Table name should match Primary Key Name and Description field (SalesType – SalesTypeId, SalesTypeDescription)
  • Do not prefix with tbl_ or sp_
  • Name code by object name (CustomerSearch, CustomerGetBalance)
  • CamelCase database object names
  • Column names should be singular
  • Table names may be plural
  • Give business names to all constraints (MustEnterFirstName)

Data Types

  • Use same variable type across tables (Zip code – numeric in one table and varchar in another is not a good idea)
  • Use nNVarChar for customer information (name, address(es)) etc. you never know when you may go multinational

In code

  • Keywords always in UPPERCASE
  • Never use implied joins (Comma syntax) - always use explicit INNER JOIN / OUTER JOIN
  • One JOIN per line
  • One WHERE clause per line
  • No loops – replace with set based logic
  • Use short forms of table names for aliases rather than A, B, C
  • Avoid triggers unless there is no recourse
  • Avoid cursors like the plague (read http://www.sqlservercentral.com/articles/T-SQL/66097/)

Documentation

  • Create database diagrams
  • Create a data dictionary

Normalization and Referential Integrity

  • Use single column primary keys as much as possible. Use unique constraints where required.
  • Referential integrity will be always enforced
  • Avoid ON DELETE CASCADE
  • OLTP must be at least 4NF
  • Evaluate every one-to-many relationship as a potential many-to-many relationship
  • Non user generated Primary Keys
  • Build Insert based models instead of update based
  • PK to FK must be same name (Employee.EmployeeId is the same field as EmployeeSalary.EmployeeId)
  • Except when there is a double join (Person.PersonId joins to PersonRelation.PersonId_Parent and PersonRelation.PersonId_Child)

Maintenance : run periodic scripts to find

  • Schema without table
  • Orphaned records
  • Tables without primary keys
  • Tables without indexes
  • Non-deterministic UDF
  • Backup, Backup, Backup

Be good

  • Be Consistent
  • Fix errors now
  • Read Joe Celko's SQL Programming Style (ISBN 978-0120887972)
倦话 2024-07-30 10:10:22

我对 Oracle 的标准是:

  • 关键字总是大写;
  • 数据库对象名称始终为小写;
  • 下划线将取代空格(即不会有任何常见的驼峰大小写约定,例如 SQL Server);
  • 主键几乎总是被命名为“id”;
  • 将强制执行参照完整性;
  • 整数值(包括表 ID)通常始终为 NUMBER(19,0)。 这样做的原因是,这将适合 64 位有符号整数,从而允许使用 Java long 类型,而不是更尴尬的 BigInteger;
  • 尽管将“_number”附加到某些列名是用词不当,但此类列的类型将是 VARCHAR2 而不是数字类型。 数字类型保留给主键和您进行算术运算的列;
  • 我总是使用技术主键; 每个
  • 表都有自己的密钥生成顺序。 该序列的名称将为 _seq。

对于 SQL Server,唯一的修改是对数据库对象名称使用驼峰式大小写(即 PartyName 而不是 party_name)。

查询往往会编写为多行,每行一个子句或条件:

SELECT field1, field2, field2
FROM tablename t1
JOIN tablename2 t2 ON t1.id = t2.tablename_id
WHERE t1.field1 = 'blah'
AND t2.field2 = 'foo'

如果 SELECT 子句足够长,我会将其拆分为每行一个字段。

My standards for Oracle are:

  • Keywords are always in UPPERCASE;
  • Database object names are always in lowercase;
  • Underscores will replace spaces (ie there won't be any camel case conventions that are common on, say, SQL Server);
  • Primary keys will pretty much always be named 'id';
  • Referential integrity will be enforced;
  • Integer values (including table ids) will generally always be NUMBER(19,0). The reason for this is that this will fit in a 64-bit signed integer thus allowing the Java long type to be used instead of the more awkward BigInteger;
  • Despite the misnomer of appending "_number" to some column names, the type of such columns will be VARCHAR2 not a number type. Number types are reserved for primary keys and columns you do arithmetic on;
  • I always use a technical primary keys; and
  • Each table will have its own sequence for key generation. The name of that sequence will be _seq.

With SQL Server, the only modification is to use camel case for database object names (ie PartyName instead of party_name).

Queries will tend to be written multi-line with one clause or condition per line:

SELECT field1, field2, field2
FROM tablename t1
JOIN tablename2 t2 ON t1.id = t2.tablename_id
WHERE t1.field1 = 'blah'
AND t2.field2 = 'foo'

If the SELECT clause is sufficiently long I'll split it out one field per line.

剑心龙吟 2024-07-30 10:10:22
  • 列出所有约束条件
  • Name all constraints
晨光如昨 2024-07-30 10:10:22

不要忘记定期备份数据库。

don't forget to back up your databases on a regular basis.

今天小雨转甜 2024-07-30 10:10:22
  1. 不要在字段名称中使用类型名称。 年长的人会记得 lpszFieldName 的旧 MS 标准以及随之而来的愚蠢行为。

  2. 使用遵循正常语言约定的描述性字段名称。 例如,“FirstName”而不是“NameFirst”

  3. 字段名称中的每个单词均大写

  4. 无下划线

  5. 不要使用普通关键字,例如“Index”

  6. 不要在对象类型前添加任何前缀。 例如,我们不使用 tblCustomers 或 spCustomersGet。 这些不允许进行良好的排序并提供零值。

  7. 使用架构来定义数据库的单独区域。 例如 sales.Customers 和 hr.Employees。 这将消除人们使用的大部分前缀。

  8. 任何类型的循环都应该被怀疑。 通常有一种更好的基于集合的方法。

  9. 使用视图进行复杂的连接。

  10. 尽可能避免复杂的连接。 拥有一个 CustomerPhoneNumbers 表可能会更美观; 但说实话,我们真正需要存储多少个电话号码? 只需将字段添加到“客户”表中即可。 您的数据库查询将会更快并且更容易理解。

  11. 如果一个表调用字段“EmployeeId”,则引用它的每个表都应使用该名称。 它不需要仅仅因为它位于扩展表中而被称为 CustomerServiceRepId。

  12. 几乎所有表格都以“s”结尾。 例如:Customers、Orders 等。毕竟表中保存了很多记录...

  13. 使用分析工具评估您的查询、索引和外键关系。 即使是那些可能为您生成的。 您可能会感到惊讶。

  14. 支持多对多关系的链接表的名称中包含两个链接表。 例如,学校成绩。 通过表名很容易看出它的作用。

  15. 保持一致。 如果您按照约定开始一条道路,请不要半途而废,除非您愿意重构所有先前的工作。 这应该会阻止任何“如果……岂不是很棒”的想法,这些想法最终会导致混乱和大量返工。

  16. 打字前请三思。 您真的需要该表、字段、存储过程或视图吗? 你确定它没有被其他地方覆盖吗? 在添加之前取得共识。 如果由于某种原因您必须将其取出,请先与您的团队联系。 我曾经遇到过这样的地方,DBA 每天都会进行重大更改,而不考虑开发人员。 这并不有趣。

  1. Don't use type names in the field names. The older guys will remember the old MS standard of lpszFieldName and the stupidity that ensued.

  2. Use descriptive field names That follow normal language conventions. For example "FirstName" instead of "NameFirst"

  3. Each word in the field name is capitalized

  4. No underscores

  5. Do not use normal keywords such as "Index"

  6. Do not prefix ANYTHING with the object type. For example we do NOT use tblCustomers or spCustomersGet. These don't allow for good sorting and provide zero value.

  7. Use schemas to define separate areas of the database. Such as sales.Customers and hr.Employees. This will get rid of most of the prefixes people use.

  8. Loops of any kind should be viewed with suspicion. There's usually a better set based way.

  9. Use views for complicated joins.

  10. Avoid complicated joins when possible. It may be more astheticaly pleasing to have a CustomerPhoneNumbers table; but honestly, how many phone numbers do we really need to store? Just add the fields to the Customers table. Your DB queries will be faster and it's much easier to understand.

  11. If one table calls a field "EmployeeId" then EVERY SINGLE TABLE that references it should use that name. It doesn't need to be called CustomerServiceRepId just because it's in an extension table.

  12. Almost all tables have the "s" ending. For example: Customers, Orders, etc. After all the table holds many records...

  13. Evaluate your queries, indexes and foreign key relationships with an analysis tool. Even those that may be generated for you. You might be surprised.

  14. Linking tables which support many to many relationships have both linked tables in the name. For example, SchoolsGrades. It's very easy to tell by the table name what it does.

  15. Be CONSISTENT. If you start down one path with your conventions, don't change horses halfway unless you are willing to refactor all of the previous work. This should put the brakes on any "wouldn't it be great if.." ideas that end up causing confusion and vast amounts of rework.

  16. Think before you type. Do you really need that table, field, sproc, or view? Are you sure it isn't covered somewhere else? Get concensus before adding it. And if for some reason you have to take it out, talk to your team first. I've been at places where the DBA's make daily breaking changes without regard for the devs. This isn't fun.

我的鱼塘能养鲲 2024-07-30 10:10:22

如果数据库用于特定应用程序,则应有一个版本表,以便可以根据代码版本检查数据库版本(除其他原因外)。

If a database is for a particular application, have a version table so that the database releases can be checked against the code releases (amongst other reasons).

感性不性感 2024-07-30 10:10:22

我总是尽量不使用字段名称中的类型 - “sFirstName”、“sLastName”或“iEmployeeID”。 虽然它们一开始是匹配的,但如果发生变化,它们就会不同步,并且稍后更改这些名称会非常令人头疼,因为您还必须更改依赖对象。

Intellisense 和 GUI 工具使得找出列的类型变得很简单,所以我认为这没有必要。

I always try not to use the type in the field name - "sFirstName", "sLastName", or "iEmployeeID". While they match at first, if something changes, they'll be out of sync, and it's a huge headache to change those names later, since you have to change the dependant objects as well.

Intellisense and the GUI tools make it trivial to find out what type a column is, so I don't feel this is necessary.

荭秂 2024-07-30 10:10:22

WITH 子句确实有助于将查询分解为可管理的部分。

它还确实有助于提高查询执行计划的效率。

The WITH clause really helps break queries down into manageable parts.

It also really helps for efficiency on the execution plans of the queries.

羞稚 2024-07-30 10:10:22

确保每个 varchar/nvarchar 选择都是合适的。

确保每个 NULLable 列的选择都是适当的 - 尽可能避免 NULLable 列 - 允许 NULL 应该是合理的位置。

无论您可能从此处的建议中使用任何其他规则,我都会在数据库中创建一个可以定期运行的存储过程,以确定您拥有的任何规则或标准的系统运行状况(其中一些是一点 SQL -特定于服务器):

  • 在由于某种原因无法使用 DBMS 系统的引用完整性的任何情况下查找孤立记录(在我的系统中,我有一个进程表和一个测试表 - 所以我的 system_health SP 会查找进程没有测试,因为我只有单向 FK 关系)

  • 查找空架构

  • 查找没有主键的表

  • 查找没有任何索引的表

  • 查找没有文档的数据库对象(我们使用 SQL Server 扩展属性将文档放入数据库中) - 此文档可以像一样细化)。

  • 查找特定于系统的问题 - 需要存档的表、不属于正常每月或每日处理的异常、带有或不带有默认值的某些常见列名称(例如 CreateDate)。

  • 查找非确定性 UDF

  • 查找 TODO 注释,以确保数据库中的代码不存在未经测试或预发布的代码。

所有这些都可以自动化,让您全面了解系统健康状况。

Ensure that every varchar/nvarchar choice is appropriate.

Ensure that every NULLable column choice is appropriate - avoid NULLable columns where possible - allowing NULL should be the justifiable position.

Regardless of any other rules you might use from the suggestions here, I would create a stored procedure in the database that can be run on a regular basis to determine system health for any rules or standards you do have (some of this is a little SQL-Server specific):

  • Look for orphaned records in any cases where the DBMS system's referential integrity cannot be used for some reason (in my system I have a table of processes and a table of tests - so my system_health SP looks for processes without tests, since I only have a one-way FK relationship)

  • Look for empty schemas

  • Look for tables without primary keys

  • Look for tables without any indexes

  • Look for database objects without documentation (we use SQL Server Extended properties to put the documentation in the database - this documentation can be as granular as the column).

  • Look for system-specific issues - tables which need to be archived, exceptions which are not part of normal monthly or daily processing, certain common column names with or without defaults (CreateDate, say).

  • Look for non-deterministic UDFs

  • Look for TODO comments to ensure that code in the DB does not somehow have untested or pre-release code.

All this can be automated to give you an overall picture of system health.

伴梦长久 2024-07-30 10:10:22

每个人都以相同的基本格式编写 SQL 查询(视图、存储过程等)。 它确实有助于以后的开发/维护工作。

Everyone writes SQL queries (views, stored procedures, etc) in the same basic format. It really helps development/maintenance efforts down the road.

凯凯我们等你回来 2024-07-30 10:10:22

一致的命名标准。 让每个人都在同一页面上,使用相同的格式(无论是驼峰式大小写、特定前缀等)有助于准确地维护系统。

Consistent naming standards. Having everyone on the same page, using the same format (whether it be Camel Case, specific prefixes, etc..) helps in being able to maintain a system accurately.

美人如玉 2024-07-30 10:10:22

一些喜欢和不喜欢的。

我的观点是前缀在各个方面都很糟糕。 我目前在一个系统上工作,其中表带有前缀,表中的列以 2 个字母的表名缩写词为前缀,我每天至少浪费 30 分钟在这个数据库上工作,因为缩写词不合逻辑。 如果您想用前缀来表示某些内容,请改用架构所有者。

如果有轻微的提示表明文本数据需要支持多语言字符,请从项目一开始就使用 NVarchar。 由于缺乏前瞻性规划和思考而升级大型数据库既痛苦又浪费时间。

将 where 子句中的每个条件拆分到新行中以提高可读性(in 和 not 包含在括号中并使用 tab 键的语句。)我认为这对我来说是重要的标准。

我在一家公司工作,该公司的标准是在执行参数或变量声明时必须始终将逗号放在行的开头。 这显然使它更具可读性,但我发现这完全是一场噩梦。

A few likes and dislikes.

My opinion is prefixes are horrible in every aspect. I currently work on a system where the tables are prefixed, and the columns within the tables are prefixed with 2 letter table name acronyms, I waste at least 30 mins each day working on this database because the acronym isn't logical. If you want to denote something with a prefix use a schema owner instead.

Using NVarchar from the start of a project if there is even a slight hint that down the line the text data will need to support multi lingual chars. Upgrading large databases because of lack of forward planning and thinking is a pain and wastes time.

Splitting each condition within a where clause onto a new line for readability (in and not in statements wrapped in brackets and tabbed in.) I think this is the important standard for me.

I worked at one company where a standard was that comma's must always be placed at the start of a line when performing parameter or variable declarations. This apparently made it more readable however I found it a complete nightmare.

じ违心 2024-07-30 10:10:22

除了标准化为 3NF 或 BCNF(更多信息请参见这个问题),我发现以下内容很有用:

  • 名称表作为复数名词
  • 将列命名为单数

因此“People”表有一个“PersonID”列。

  • 只要 3NF 或 BCNF 规则仍然成立,复合键就没有问题。 在许多情况下(例如“多对多”情况)这是完全可取的。
  • 避免在列名中重复表名。 无论如何,peoplePersonID 最好写成 table.column,并且更具可读性,因此可以自我记录。 People.PersonID 更好,至少对我来说。
  • ON DELETE CASCADE 应非常小心使用。
  • 请记住,NULL 表示以下两种情况之一:未知或不适用。
  • 还请记住,NULL 对连接有有趣的影响,因此请练习 LEFT、RIGHT 和 FULL 外连接。

In addition to normalization to 3NF or BCNF (more about that in this question), I have found the following to be useful:

  • Name tables as plural nouns
  • Name columns as sigular

So a "People" table has a "PersonID" column.

  • There is nothing wrong with composite keys, so long as the rules of 3NF or BCNF still hold. In many cases (such as the "many-to-many" case) this is entirely desirable.
  • Avoid repeating the table name in the column names. peoplePersonID is better written as table.column anyway, and much more readable and therefore self-documenting. People.PersonID is better, to me at least.
  • ON DELETE CASCADE should be used very carefully.
  • Remember that NULL means one of two things: Either it's unknown or it's not applicable.
  • Remember also that NULLs have interesting affects on joins, so practice your LEFT, RIGHT, and FULL outer joins.
琴流音 2024-07-30 10:10:22

其他一些(尽管很小)的评论值得一提...

SQL Server 数据库模式对于组织表和存储过程以及控制安全性都很有用。

每个事务表都应该始终跟踪记录的创建者和创建时间,以及在单独的列中更新记录。 我见过简单地使用“更新日期”的实现,这可能会导致未来的审计挑战。

对于具有离线/同步要求的项目,使用 GUID 作为所有行的行标识符。

Some others (albeit small) comments to throw against the wall...

SQL Server database schemas can be useful for both organizing tables and stored procedures as well as controlling security.

Every transactional table should always track both who and when created the record as well as updated the record in separate columns. I've seen implementation that simply used "update date" which can lead to auditing challenges in the future.

Use GUID's for row identifiers for all rows for projects with offline/synchronization requirements.

看海 2024-07-30 10:10:22

良好的数据库设计和规范化

Good database design and normalization.

秋风の叶未落 2024-07-30 10:10:22
  • 表以单数命名,小写,无下划线,无前缀
  • 字段也是小写,无下划线,无前缀
  • 存储过程以“st_”为前缀(排序很好)
  • 像表一样处理的视图没有前缀
  • 为特殊报告等创建的视图. 有“v”前缀
  • 为性能而创建的索引视图有“ixv”前缀
  • 所有索引都有有目的的名称(无自动命名)
  • 对于代理键,强烈推荐 uniqueidentifier(具有顺序增量)而不是 int IDENTITY
  • 不要人为地限制 VARCHAR/ NVARCHAR 字段为 100 或 255。给他们喘息的空间。 现在不是 20 世纪 80 年代,字段存储时并没有填充到最大长度。
  • 3NF 最低标准
  • 优先选择连接表而不是列级外键:随着系统随着时间的推移而增长,许多 1:m 假设会受到挑战。
  • 始终使用代理键而不是自然键作为主键。 所有关于“自然”密钥(SSN、用户名、电话号码、内部代码等)的假设最终都将受到挑战。
  • Tables are named in the singular, lowercase, no underscores, no prefix
  • Fields also lowercase, no underscores, no prefix
  • Stored procedures prefixed with "st_" (sorts nicely)
  • Views that are treated like tables have no prefix
  • Views created for special reports, etc. have a "v" prefix
  • Indexed views created for performance have an "ixv" prefix
  • All indexes have purposeful names (no auto-naming)
  • Strongly prefer uniqueidentifier (with sequential increment) over int IDENTITY for surrogate keys
  • Don't artificially limit VARCHAR/NVARCHAR fields to 100 or 255. Give them room to breath. This isn't the 1980s, fields are not stored padded to their max length.
  • 3NF minimum standard
  • Prefer joining tables to column-level foreign keys: many 1:m assumptions are challenged as a system grows over time.
  • Always use surrogate keys, not natural keys, as the primary key. All assumptions about "natural" keys (SSNs, usernames, phone numbers, internal codes, etc.) will eventually be challenged.
﹏雨一样淡蓝的深情 2024-07-30 10:10:22

表格格式的 SQL。

select a.field1, b.field2
from       any_table   a
inner join blah        b on b.a_id       = a.a_id
inner join yet_another y on y.longer_key = b.b_id
where a.field_3         > 7
and   b.long_field_name < 2;

其中一部分是使用统一长的别名(在示例中,a、b 和 y 的长度均为 1)。

通过这种格式,我可以更快地回答常见问题,例如“哪个表的别名是‘a’?” 以及“哪些字段将表 T 连接到查询中?” 该结构的应用或更新不需要很长时间,而且我发现它节省了大量时间。 我们阅读代码的时间多于编写代码的时间。

Tabular formatted SQL.

select a.field1, b.field2
from       any_table   a
inner join blah        b on b.a_id       = a.a_id
inner join yet_another y on y.longer_key = b.b_id
where a.field_3         > 7
and   b.long_field_name < 2;

Part of this is to use uniformly long alias names (in the example, here, a, b, and y are all length 1).

With this kind of formatting, I can more quickly answer common questions like, "what table is aliased by 'a'?" and "which fields join table T into the query?" The structure doesn't take long to apply or to update, and I find that it saves a lot of time. We spend more time reading code than writing it.

回梦 2024-07-30 10:10:22

记录一切; wiki 类型的文档很容易设置,而且该软件是免费的。

确保您首先了解界面,然后设计数据库。 大多数时候,最好了解您将要使用的数据如何工作,然后设计数据库。 大多数糟糕的数据库设计都是随着事物的发展而不是预先发生的。

然后定义您要使用的数据库标准和版本。 定义代码元素(视图、函数等)、数据库命名的标准; 列、表的命名约定; 列的类型约定; 编码模板。

花时间考虑如何定义具有标准数据库类型的字段或定制类型的类型是预先理清的好事情。

作为文档的一部分,包括应用程序的禁止事项和注意事项列表,其中包括您最喜欢的讨厌的功能光标、触发器。

定期查看。

Document everything; wiki type documentation is easy to setup and the software is free.

Make sure you understand the interface first and design the database second. Most of the time its a lot better to know how the data you are going to use needs to work and then engineer the database. Most bad DB design happens as things evolve not upfront.

Then define the database standard and version you are going to work to. Define standards for the code elements (views, functions etc), database naming; naming conventions for columns, tables; type conventions for columns; coding templates.

Spend time considering how you define types having standard database types for fields or bespoke types are a good thing to sort out upfront.

As part of your documentation include a list of don'ts as well as dos for the application which include your prefered hated functionality cursors, triggers.

Review it regularly.

乞讨 2024-07-30 10:10:22

13-评估您的查询

确实如此。 有时你并没有得到你想要的。

对我来说,用准确的内容命名表和字段总是有用的,并且(对我们来说)使用清晰的西班牙语并使用大驼峰式大小写,没有空格:

用户名:NombreUsuario

名字:ApellidoPaterno

第二个姓氏:ApellidoMaterno

等等

13- Evaluate your queries

Thats true. Sometimes you don't get what you wanted.

For me, it's always useful to name the tables and fields with their exact content and (for us) in clear spanish and using Upper Camel Case, with no whitespaces:

User Name: NombreUsuario

First Last Name: ApellidoPaterno

Second Last Name: ApellidoMaterno

etc etc

最单纯的乌龟 2024-07-30 10:10:22

将“数据库”理解为“SQL 产品”,我的回答是,“太多了,无法提及。你可以就这个主题写一整本书。” 值得庆幸的是,有人做到了。

我们使用 Joe Celko 的 SQL 编程风格(ISBN 978-0120887972):“这本书是启发式和规则、提示和技巧的集合,将帮助您提高 SQL 编程风格和熟练程度,并用于格式化和编写可移植、可读、可维护的SQL 代码。”

这种方法的优点包括:

  • 这个人比我更了解这种事情(还有另一本关于 SQL 启发式的书吗?!);
  • 工作已经完成,例如我可以将这本书交给团队中的某人阅读和参考;
  • 如果有人不喜欢我的编码风格,我可以责怪别人;
  • 最近,我通过推荐另一本 Celko 的书而得到了很多人的认可:)

在实践中,我们确实偏离了这本书的规定,但令人惊讶的是很少。

Taking "database" to mean "SQL product", my answer is, "Too many to mention. You could write a whole book on the subject." Happily, someone has.

We use Joe Celko's SQL Programming Style (ISBN 978-0120887972): "this book is a collection of heuristics and rules, tips, and tricks that will help you improve SQL programming style and proficiency, and for formatting and writing portable, readable, maintainable SQL code."

Advantages of this approach is include:

  • the guy knows more about this kind of thing than me (is there another book on SQL heuristics?!);
  • the work has already been done e.g. I can give the book to someone on the team to read and refer to;
  • if someone doesn't like my coding style I can blame someone else;
  • I recently got a load of rep on SO by recommending another Celko book :)

In practice we do deviate from the prescriptions of The Book but surprisingly rarely.

残花月 2024-07-30 10:10:22

在 MS-SQL 中,我始终拥有 dbo. 拥有的对象,并且我在对这些对象的调用前加上 dbo. 前缀。

我多次看到我们的开发人员想知道为什么他们不能调用他们无意中拥有的对象。

In MS-SQL, I've always had objects owned by dbo., and I prefix calls to those objects with dbo.

Too many times I've seen our devs wonder why they can't call their objects that they inadvertainly owned.

小镇女孩 2024-07-30 10:10:22

避免愚蠢的缩写约定,例如积极鼓励像 EMP_ID_CONV_FCTR_WTF_LOL_WAK_A_WAK_HU_HU 这样的怪物的综合缩写词典。 这条规则的灵感来自于我以前见过的一套真实的指导方针。

Avoid silly abbreviation conventions, such as comprehensive dictionaries of abbreviations that actively encourage monstrosities like EMP_ID_CONV_FCTR_WTF_LOL_WAK_A_WAK_HU_HU. This rule is inspired a real set of guidelines I've seen before.

遮了一弯 2024-07-30 10:10:22

表名称与主键名称和描述键匹配

,经过多年的同意,我最近才同意这一点,现在每个表上都有一个“ID”列。

是的,我知道,链接表时它是不明确的! 但是将 ProductID 链接到 ProductID 也是如此,所以呃,为什么要额外输入呢?

这:

SELECT p.Name, o.Quantity FROM Products p, Orders o WHERE o.ProductID = p.ID

比这稍微好一点:

SELECT p.Name, o.Quantity FROM Products p, Orders o WHERE o.ProductID = p.ProductID

请注意,两者都需要表或别名前缀。 但我不仅打字稍微少了一些(乘以数十个具有长描述性名称的表,并且在数据密集型应用程序中加起来很快),而且还可以更容易地知道哪个表是每个连接中的父表,哪个表,当在查询中连接 8-10 个表时,可以提供很大帮助。

Table name matches Primary Key name and description key

I have just recently, after years of agreeing with this, jumped ship, and now have an "ID" column on every table.

Yes I know, when linking tables it's abiguous! But so is linking ProductID to ProductID, so uhh, why the extra typing?

This:

SELECT p.Name, o.Quantity FROM Products p, Orders o WHERE o.ProductID = p.ID

Is slightly better than this:

SELECT p.Name, o.Quantity FROM Products p, Orders o WHERE o.ProductID = p.ProductID

Note that both will require table or alias prefixes. But not only am I typing slightly less (multiply that across dozens of tables with long descriptive names and it adds up fast in a data intensive application) but it also makes it easier to know which table is the parent table in every join, which, when joining 8-10 tables in a query, can help quite a bit.

粉红×色少女 2024-07-30 10:10:22

我和这里的其他人遵循很多相同的惯例,但我想说一些尚未说过的事情。

无论您喜欢表的复数名称还是单数名称,都要保持一致。 选择其中之一,但不要同时使用两者。

表中的主键与表同名,后缀为_PK。 外键与其对应的主键具有相同的名称,但带有后缀 _FK。 例如,Product表的主键称为Product_PK; 在Order表中对应的外键是Product_FK。 我从我的另一位 DBA 朋友那里学到了这个习惯,到目前为止我很喜欢它。

每当我执行 INSERT INTO...SELECT 时,我都会为 SELECT 部分中的所有列添加别名,以匹配 INSERT INTO 部分中的列名称,从而更容易维护并查看内容如何匹配。

I follow a lot of the same conventions as others here, but I wanted to say a few things that haven't been said yet.

Regardless of whether you like plural names or singular names for your tables, be consistent. Choose one or the other, but don't use both.

The primary key in a table has the same name as the table, with the suffix _PK. Foreign keys have their same name as their corresponding primary key, but with a suffix of _FK. For example, the Product table's primary key is called Product_PK; in the Order table the corresponding foreign key is Product_FK. I picked this habit up from another DBA friend of mine and so far I'm liking it.

Whenever I do an INSERT INTO...SELECT, I alias all the columns in the SELECT portion to match the names of the columns from the INSERT INTO portion to make it easier to maintain and see how things match up.

岁月染过的梦 2024-07-30 10:10:22

最重要的标准是:默认没有数据库。 我发现太多的开发人员为项目获取数据库,而如果没有数据库,生活会容易得多(至少目前为止)。 它只是工具箱中的一个工具,并不是所有问题都是钉子。

数据库使用不当会导致域模型贫乏、代码难以测试以及不必要的性能问题。

The most important standard is: don't have a database by default. I find too many developers grabbing a database for projects where life would have been much easier without one (at least yet). It is just a tool in the toolbox, and not every problem is a nail.

Inappropriate use of a database leads to anemic domain models, badly testable code and unneeded performance problems.

夏日落 2024-07-30 10:10:22

除了#5 之外,我几乎同意你所说的一切。 我经常对表和存储过程使用前缀,因为我们开发的系统有很多不同的功能区域,所以我倾向于使用标识符为表和存储过程添加前缀,以便它们可以根据区域在 Management Studio 中很好地分组他们属于。

示例:cjso_Users、cjso_Roles,然后就有routing_Users、routing_Roles。 这听起来像是数据的复制,但实际上,两个不同的用户/角色表用于系统的完全独立的功能(cjso 用于基于客户的电子商务应用程序,而路由代表使用路由的员工和分销商)系统)。

I agree with just about everything you have put there except for #5. I often use prefixes for tables and stored procedures because the systems that we develop have lots of different functional areas, so I will tend to prefix the tables and sprocs with an identifier that will allow for them to group nicely in Management Studio based on what area they belong to.

Example: cjso_Users, cjso_Roles, and then you have routing_Users, routing_Roles. This may sound like replication of data, but in reality the two different user/roles tables are for completely separate functions of the system (cjso would be for the customer-based ecommerce app while the routing would stand for employees and distributors who use the routing system).

葬花如无物 2024-07-30 10:10:22

我喜欢我们的表命名约定:

People Table
PEO_PersonID
PEO_FirstName 
...

这有助于使更大的查询更具可读性。 和连接更有意义:

Select * -- naughty!
From People
Join Orders on PEO_PersonID = ORD_PersonID
--...

我猜想不是命名约定是什么,而是命名的一致性。

I like our table naming convention:

People Table
PEO_PersonID
PEO_FirstName 
...

Which helps make larger querys a bit more readable. and joins make a bit more sense:

Select * -- naughty!
From People
Join Orders on PEO_PersonID = ORD_PersonID
--...

i guess rather than what the naming convention is, is the consistency of the naming.

暮光沉寂 2024-07-30 10:10:21
  • 使用相同的前缀命名相似的目标存储过程,例如,如果您有 3 个针对 Person 的存储过程。 这样,人的所有内容都集中在一个地方,您可以轻松找到它们,而无需查看所有进程来找到它们。
    • 人物更新
    • 删除人员
    • 创建人员
  • 当您有包含相关数据的表组时,对表执行类似的操作。 例如:
    • 发票标题
    • 发票行
    • 发票行详细信息
  • 如果您可以选择数据库中的模式,请使用它们。 看起来更好看:
    • 发票.标题
    • 发票.行.项目
    • 发票.行.项目.详细信息
    • 人物.更新
    • 人物.删除
    • Person.Create
  • 不要使用触发器,除非没有其他合理的方法来实现该目标。
  • 为字段名称指定一个有意义的前缀,这样您就可以知道它们来自哪个表,而无需有人解释。 这样,当您看到引用的字段名称时,您可以轻松判断它来自哪个表。
  • 对包含相似数据的字段使用一致的数据类型,即不要在一个表中将电话号码存储为数字,而在另一个表中将电话号码存储为 varchar。 事实上,不要将其存储为数字,如果我遇到负数电话号码我会很生气。
  • 不要在表/字段名称中使用空格或其他晦涩的字符。 它们应该完全是字母数字的——或者如果我有我的建议的话,除了下划线之外,完全是字母数字的。 我目前正在开发一个继承系统,其中表和字段名称包含空格、问号和感叹号。 让我每天都想杀了设计师!
  • 不要使用语法关键字作为对象名称,这会导致尝试从中检索数据时遇到麻烦。 我讨厌必须将对象名称包装为 [index] 那是两个不必要的字符我不需要输入该死的你!
  • Name similarly targetted stored procs with the same prefix, for instance if you've got 3 stored procedures for Person. That way everything for person is grouped in one place and you can find them easily without having to look through all your procs to find them.
    • PersonUpdate
    • PersonDelete
    • PersonCreate
  • Do similar things for tables when you have groups of tables with related data. For instance:
    • InvoiceHeaders
    • InvoiceLines
    • InvoiceLineDetails
  • If you have the option of schemas within your database, use them. It's much nicer to see:
    • Invoice.Header
    • Invoice.Line.Items
    • Invoice.Line.Item.Details
    • Person.Update
    • Person.Delete
    • Person.Create
  • Don't use triggers unless there's no other reasonable approach to achieve that goal.
  • Give field names a meaningful prefix so you can tell what table they come from without someone needing to explain. That way when you see a field name referenced, you can easily tell which table it's from.
  • Use consistent data types for fields containing similar data, i.e. don't store phone number as numeric in one table and varchar in another. In fact, don't store it as numeric, if I come across a negative phone number I'll be mad.
  • Don't use spaces or other obscure characters in table/field names. They should be entirely alphanumeric - or if I had my druthers, entirely alphabetic with the exception of the underscore. I'm currently working on an inherited system where table and field names contain spaces, question marks and exclamation marks. Makes me want to kill the designer on a daily basis!
  • Don't use syntax keywords as object names it'll cause headaches trying to retrieve data from them. I hate having to wrap object names as [index] that's two needless chars I didn't need to type damn you!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文