从MySQL到Oracle(NOW()和自动增量ID)

时间:2011-08-09 06:40:29

标签: mysql oracle timestamp auto-increment

我真的不知道怎么问这个,但......代码会帮助我:

/**
 * Languages table definition
 */
DROP TABLE IF EXISTS `languages`;
CREATE TABLE `languages`
(
    -- Common:
    `id`      INTEGER    NOT NULL AUTO_INCREMENT                COMMENT 'Unique registry identifier',
    `created` TIMESTAMP  NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Registry creation TIMESTAMP',
    `updated` TIMESTAMP  NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT 'Registry last update TIMESTAMP',
    `active`  BOOLEAN    NOT NULL DEFAULT TRUE                  COMMENT 'Virtual deletion flag',
    PRIMARY KEY (`id`),
    -- /Common
    `language_id`   INTEGER(2)  UNSIGNED NOT NULL COMMENT 'Language identifier',
    `language_code` VARCHAR(2)           NOT NULL COMMENT 'ISO 639-1 Code',
    `language_name` VARCHAR(20)          NOT NULL COMMENT 'Language name',
    -- Indexes
    UNIQUE KEY `language_id` (`language_id`)
) ENGINE=InnoDB CHARACTER SET 'latin1' COLLATE 'latin1_general_ci';

/**
 * Updates multilang field to UTF-8
 */
ALTER TABLE `languages` MODIFY `language_name` VARCHAR(20) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

/**
 * Assigns the current TIMESTAMP to the created field without user input
 */
CREATE TRIGGER `insert_languages` BEFORE INSERT ON `languages`
    FOR EACH ROW
SET NEW.created = NOW();

/* Insert a record */
INSERT INTO languages(language_id, language_code, language_name) VALUES(10, 'es', 'Español');

/* Update that record (after a few seconds) */
UPDATE languages SET language_name = 'Español (España)' WHERE language_id = 10;

检索* WHERE language_id = 10时,会收到两个不同的时间戳,而不会显式触及TIMESTAMP字段,插入时也不需要输入ID。问题是:如何在Oracle中创建相同的行为?

1 个答案:

答案 0 :(得分:2)

  1. 您需要使用带有BEFORE INSERT触发器的序列来获取自动增量ID
  2. 您需要在触发器sysdate和{{1}中使用systimestamplocaldateNOW() ...而不是BEFORE INSERT来维护日期}}