Обсуждение: SQL (?) question

Поиск
Список
Период
Сортировка

SQL (?) question

От
"Joost Kraaijeveld"
Дата:
Hi all,

Is there an easy way (e.g. short SQL script) to add a column to a table and fill it with integers (from 1- n) just like
usingan sequence? (I need to retofit a system id that is handled in the application, not in the database). 

Groeten,

Joost Kraaijeveld
Askesis B.V.
Molukkenstraat 14
6524NB Nijmegen
tel: 024-3888063 / 06-51855277
fax: 024-3608416
e-mail: J.Kraaijeveld@Askesis.nl
web: www.askesis.nl

Re: SQL (?) question

От
Mike Mascari
Дата:
Joost Kraaijeveld wrote:

> Hi all,
>
> Is there an easy way (e.g. short SQL script) to add a column to a
> table and fill it with integers (from 1- n) just like using an
> sequence? (I need to retofit a system id that is handled in the
> application, not in the database).

I assume there is some unique candidate key on the table already (or
worst case, an OID.) If so, I'd just do:

CREATE SEQUENCE my_sequence;

CREATE TEMPORARY TABLE foo AS
SELECT candidate_key, nextval('my_sequence') as new_key
FROM table_that_needs_fixed;

ALTER TABLE table_that_needs_fixed
ADD COLUMN new_key integer;

UPDATE table_that_needs_fixed
SET new_key = foo.new_key
WHERE candidate_key = foo.candidate_key;

Add appropriate constraints as necessary...

HTH,

Mike Mascari