Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

sqlite - Use trigger for auto-increment

I'm trying to solve the problem that composite keys in sqlite don't allow autoincrement.

I don't know if it's possible at all, but I was trying to store the last used id in a different table, and use a trigger to assign the next id when inserting a new reccord.

I have to use composite keys, because a single pk wouldn't be unique (because of database merging).

How can I set a field of the row being inserted based on a value in a different table

The query so far is:

CREATE TRIGGER pk BEFORE INSERT ON product_order
BEGIN
    UPDATE auto_increment SET value = value + 1 WHERE `table_name` = "product_order";
END

This successfully updates the value. But now I need to assign that new value to the new record. (new.id).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you use an AFTER INSERT trigger then you can update the newly inserted row, as in the following example.

CREATE TABLE auto_increment (value INT, table_name TEXT);
INSERT INTO auto_increment VALUES (0, 'product_order');

CREATE TABLE product_order (ID1 INT, ID2 INT, name TEXT);

CREATE TRIGGER pk AFTER INSERT ON product_order
BEGIN

    UPDATE  auto_increment 
    SET     value = value + 1 
    WHERE   table_name = 'product_order';

    UPDATE  product_order 
    SET     ID2 = (
                SELECT value 
                FROM auto_increment 
                WHERE table_name = 'product_order')
    WHERE   ROWID = new.ROWID;
END;

INSERT INTO product_order VALUES (1, NULL, 'a');
INSERT INTO product_order VALUES (2, NULL, 'b');
INSERT INTO product_order VALUES (3, NULL, 'c');
INSERT INTO product_order VALUES (4, NULL, 'd');

SELECT * FROM product_order;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...