Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

sql - SET IDENTITY_INSERT postgresql

I'm not familiar with postgresql script.

I already use this script in ms sql server :

SET IDENTITY_INSERT my_table ON
INSERT INTO my_table (
  my_identity_field,
  field1,
  field2
) 
SELECT 
  fieldA,
  fieldB
FROM
  my_other_table
WHERE
  fieldC = some_value
SET IDENTITY_INSERT my_table OFF

Question : What is the script 'SET IDENTIFY_INSERT [table_name] ON/OFF' in PostgreSQL ?

Thank you

SOLVED :

INSERT INTO my_table (
  my_identity_field,
  field1,
  field2
) 
SELECT 
  fieldA,
  fieldB
FROM
  my_other_table
WHERE
  fieldC = some_value;

SELECT 
setval(pg_get_serial_sequence('my_table', 'my_identity_field'), 
(SELECT MAX(my_identity_field) FROM my_table));

Note: 'my_table' and 'my_identity_field' in lowercase I'm getting error if they're not in lowercase (all letters)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You don't need set identity_insert in Postgres.

Just insert the data into your table.

What you need to do however, is to re-sync the sequences that's behind your serial ("auto increment") column using the setval() function:

select setval(pg_get_serial_sequence('my_table', 'my_serial_column'), 
              (select max(my_serial_column) from my_table) 
       ); 

If the column is not defined as a serial but "only" has a default value taken from a sequence, you need to supply the sequence name "manually"

select setval('my_sequence_name', (select max(my_serial_column) 
                                   from my_table)
       ); 

Edit

Here is an SQLFiddle example: http://sqlfiddle.com/#!15/690ea/1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...