Re: Any way to insert rows with ID used in another column
От | Adrian Klaver |
---|---|
Тема | Re: Any way to insert rows with ID used in another column |
Дата | |
Msg-id | 533D7747.2080101@aklaver.com обсуждение исходный текст |
Ответ на | Any way to insert rows with ID used in another column (Ben Hoyt <benhoyt@gmail.com>) |
Список | pgsql-general |
On 04/03/2014 07:41 AM, Ben Hoyt wrote: > Hi folks, > > We have a table images in our db with id (serial primary key) and > filename columns, where the filename is a unique text column that looks > something like "pool-1234.jpg". > > The catch is that the "1234" in the filename is the image ID. We want > the filename to include the image ID because it's a nice way of making > it unique and gives the benefit of being able to easily map from the > filename back to the ID for debugging and the like. > > Currently I insert new image rows in multiple steps: > > 1) begin transaction > 2) insert a whole bunch of image rows in one multiple-row INSERT, using > a temporary random filename > 3) use the RETURNING clause on the above insert to get a mapping between > the database IDs and filenames just inserted > 4) loop through all images just inserted, and for each image, execute > UPDATE to set the filename to the real filename which includes the new > image ID > 5) commit > > This works, but it's pretty cumbersome, and requires N UPDATE statements > which is also slow. > > Is there some way to do something like this: > > INSERT INTO images (filename) VALUES > ('foo' || image_id_about_to_used_for_this_row::text || '.jpg') > ('bar' || image_id_about_to_used_for_this_row::text || '.jpg') > > I tried using currval() to see if that'd work, but it gave an error, I > guess because I was using it multiple times per session. Write a BEFORE INSERT trigger function? > > Thanks, > Ben > -- Adrian Klaver adrian.klaver@aklaver.com
В списке pgsql-general по дате отправления: