For example:
- IDENTITY column
That's a column of a table which is generated automatically, typically in an ever increasing fashion. 点击(此处)折叠或打开
- CREATE TABLE emp(empid INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
- name VARCHAR(20),
- salary DECIMAL(10, 2));
- INSERT INTO emp VALUES(DEFAULT, 'Jones', 20000);
- VALUES IDENTITY_VAL_LOCAL();
- 1
- ---------------------------------
- 1.
- 1 record(s) selected.
An identity column is typically unique within the table unless you allow it to cycle, you reset it or allow overriding of the generation by LOAD or INSERT.- SEQUENCE object
A sequence is like an identity column, but without being attached to a table. Typically a sequence generates unique numbers within the database unless you allow it to cycle or reset it, - GENERATE_UNIQUE()
A function that generates a unique CHAR(13) FOR BIT DATA (binary) string based on the current time and information about nodes in a DB2 cluster. The result is unique across the database as long as the system clock is not reset.
To produce universally unique identifiers (UUID) various well defined algorithms are available which use a combination of time or random number generation and machine unique information such as MAC addresses to produce binary strings that have a very, very low likelihood of colliding.
DB2 does not natively support UUID, but Java does. So here I provide a sample implementation of UUID based on Java.
Let's get started:
- Ensure javac the java compiler is on your path.
It's normally on sqllib\java\jdk\bin - Create a java file named UUIDUDF.java
- compile the program from your shell
- Produce a jar file
- Time to fire up DB2
- Connect to the database
- Register the jar file with the database You may want to move the JAR file to a safe place and adjust the path above accordingly.
in a multi-member environment, make sure the file is accessible from all members. - Create the function:
- Test the function What you see is the generally accepted pretty-printed form of UUIDs.
- db2 provides two functions VARCHAR_BIT_FORMAT() and VARCHAR_FORMAT_BIT() to convert the pretty printed version to a binary string and vice versa. This is a 16 byte long VARCHAR FOR BIT DATA.
- To make things nice and tight let's produce another function that gets us the binary string right away as a CHAR(16) FOR BIT DATA. We pick SYS_GUID() as a name to please the Oracle crowd.
- Now let's tie this all up with an example usage.