Create PostgreSQL ROLE (user) if it doesn't exist

前端 未结 10 1781
旧时难觅i
旧时难觅i 2020-12-12 15:47

How do I write an SQL script to create a ROLE in PostgreSQL 9.1, but without raising an error if it already exists?

The current script simply has:

CR         


        
10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 16:24

    As you are on 9.x, you can wrap that into a DO statement:

    do 
    $body$
    declare 
      num_users integer;
    begin
       SELECT count(*) 
         into num_users
       FROM pg_user
       WHERE usename = 'my_user';
    
       IF num_users = 0 THEN
          CREATE ROLE my_user LOGIN PASSWORD 'my_password';
       END IF;
    end
    $body$
    ;
    

提交回复
热议问题