DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
-- create som data to play with
CREATE TABLE bagger
( player_id CHAR(6)
, tralala varchar
);
-- populate the table
INSERT INTO bagger(player_id,tralala)
SELECT gs::text, 'zzz_' || gs::text
FROM generate_series(1,10) gs
;
SELECT * FROM bagger;
--
-- create the sequence, change the datatype and bind it to the sequence
--
CREATE SEQUENCE player_id_seq;
ALTER TABLE bagger
ALTER COLUMN player_id TYPE INTEGER USING player_id::integer
, ALTER COLUMN player_id SET NOT NULL
, ALTER COLUMN player_id SET DEFAULT nextval('player_id_seq')
;
ALTER SEQUENCE player_id_seq
OWNED BY bagger.player_id
;
--
-- reset the sequence to containe the maximum occuring player_id in the table
--
SELECT setval('player_id_seq', mx.mx)
FROM (SELECT MAX(player_id) AS mx FROM bagger) mx
;
SELECT * FROM bagger;
\d bagger
出力:
DROP SCHEMA
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 10
player_id | tralala
-----------+---------
1 | zzz_1
2 | zzz_2
3 | zzz_3
4 | zzz_4
5 | zzz_5
6 | zzz_6
7 | zzz_7
8 | zzz_8
9 | zzz_9
10 | zzz_10
(10 rows)
CREATE SEQUENCE
ALTER TABLE
setval
--------
10
(1 row)
player_id | tralala
-----------+---------
1 | zzz_1
2 | zzz_2
3 | zzz_3
4 | zzz_4
5 | zzz_5
6 | zzz_6
7 | zzz_7
8 | zzz_8
9 | zzz_9
10 | zzz_10
(10 rows)
Table "tmp.bagger"
Column | Type | Modifiers
-----------+-------------------+-----------------------------------------------------
player_id | integer | not null default nextval('player_id_seq'::regclass)
tralala | character varying |