开发者

Preventing duplicate rows when using UUIDs for primary key

开发者 https://www.devze.com 2023-03-21 23:36 出处:网络
I\'ve got a database table in DB2 (v9.5) like the following: CREATE TABLE license(key CHAR(16) FOR BIT DATA NOT NULL PRIMARY KEY,

I've got a database table in DB2 (v9.5) like the following:

CREATE TABLE license(key CHAR(16) FOR BIT DATA NOT NULL PRIMARY KEY, 
                     name VARCHAR(32) not null,
                     startDate TIMESTAMP not null, 
                     data XML);

(I'm using UUIDs for the primary key as shown in this guide)

My question is one of preventing duplicate entries. My duplicate criteria are as follows:

  • Duplicate column values are ok. e.g. The name value "Fred" can appear more than once in the table
  • Duplicate rows (ignoring the key) are not ok. i.e. Two rows cannot have identical values for name AND startDate AND data.

The way I see it I have a few options:

  1. Use something I've missed in the DB2 configuration to make sure that combinations of column values (i.e. name AND startDate AND data) must be unique within the table
  2. I have simply made a poor choice of primary key. Should I instead hash the value of the combined fields into a SHA-1 hash (is this a good/bad choice?) and then use that as the primary key. If so, can I just do a String concatenation of the fields into one long String and use BouncyCastle to do the heavy-lifting for me?
  3. Prior to doing an INSERT, search the table for the row I'm about to insert and don't insert it if it exists already. I don't know about the efficiency of this (or even how to do it - my DB2 XML k开发者_运维技巧nowledge is a bit lacking at the moment - but that's perhaps worth a separate question).
  4. Something else?


You can add a unique constraint. Columns can be part of a unique constraint in DB2 only if they are not nullable. Another problem here is the data column of type XML. A column of type XML cannot be part of a unique constraint.

You can add a unique constraint for columns name and startdate like this:

CREATE TABLE license(
    key CHAR(16) FOR BIT DATA NOT NULL PRIMARY KEY,
    name VARCHAR(32) not null,
    startDate TIMESTAMP not null,
    data XML,
    unique(name, startDate)
);

You can add a part of the XML column to the unique constraint. I cannot give an example here, as it depends on the specific content of your xml data. Search for "GENERATE KEY USING xmlpattern" for information on this subject.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号