[Oracle]为布尔字段值选择一种高效的设计策略

来源:互联网 发布:plc编程软件手机版 编辑:程序博客网 时间:2024/06/03 19:46

在设计数据库表结构时,选择一种高效的策略来存储一个可以在很多编程环境中使用的逻辑布尔值是非常重要的。(虽然 Oracle 没有 Boolean 数据类型来表示数据库字段,但是在 PL/SQL 中却具有 Boolean 数据类型。)

任何布尔定义的字段还应该被正确进行约束检查,以确保在插入/更新时输入了有效的值。

create table tbool (bool char check (bool in ('N','Y'));
insert into tbool values ('N');
insert into tbool values ('Y');

最常见的设计是模拟很多 Oracle 的数据字典视图中使用的类似布尔的标志,选择‘Y’表示真,‘N’表示假。然而,要正确地与宿主环境交互,比如与 JDBC、OCCI 和其它编程环境交互,最好选择0表示,选择1表示,从而使getBoolean 和setBoolean 能够正确地处理它们。

We could define a Boolean as NUMBER(1); however, in Oracle's internal number format, 0 takes 1 byte and 1 takes 2 bytes after the length byte (so it's more efficient to store it as CHAR). Even though the character is defined as CHAR, SQL can convert and verify against actual numbers.

我们可以将一个布乐类型定义为 NUMBER(1);然而,在 Oracle 的内部数字格式中,0在长度字节之后占用一个字节,而1在长度字节之后占用两个字节(所以更加高效地方式是将其存储为 CHAR)。即使字符被定义为 CHAR,SQL 也可以转换和验证实际的数字。

create table tbool (bool char check (bool in (0,1));
insert into tbool values(0);
insert into tbool values(1);

 
原创粉丝点击