通过数据库链接在另一个数据库上创建用户

时间:2015-01-17 13:39:10

标签: database oracle stored-procedures database-link

我想通过数据库链接在另一个数据库上创建用户。我在执行程序时遇到错误。 这是我使用的代码。

create or REPLACE PROCEDURE hostname   
(host_name in varchar2,user_name in VARCHAR2, pass_word in VARCHAR2,    
table_space in varchar2,pro_file in varchar2)    
as    
db_link_name varchar2(30);    
begin    
select db_link into db_link_name from all_db_links where host=host_name;    
EXECUTE IMMEDIATE 'dbms_utility.exec_ddl_statement@'||db_link_name||('CREATE     USER '||user_name||' IDENTIFIED BY '||pass_word||'     
DEFAULT TABLESPACE '||table_space||' PROFILE '|| pro_file||' ACCOUNT UNLOCK');    
EXECUTE IMMEDIATE 'dbms_utility.exec_ddl_statement@'||db_link_name||    
('GRANT CONNECT,RESOURCE,EXECUTE_CATALOG_ROLE,Create table,create session,create     view,create sequence,create procedure,create job,create synonym TO '||user_name);    
end;    
/    
execute hostname('orcl1','rahul1','rahul','users','default');    
  

错误:ORA-00900:无效的SQL语句ORA-06512:at   “SYS.HOSTNAME”,第6行ORA-06512:第1行   00900. 00000 - “无效的SQL语句”
  *原因:
  *操作:

1 个答案:

答案 0 :(得分:3)

我想你可能会对评论者mustaccio提供的一些建议感到有些困惑。他的意思是,EXECUTE IMMEDIATE语句中的SQL字符串需要使用PL / SQL块来调用存储过程。

换句话说,而不是写

EXECUTE IMMEDIATE 'dbms_utility.exec_ddl_statement ... ';

你应该写

EXECUTE IMMEDIATE 'BEGIN dbms_utility.exec_ddl_statement ... ; END;';

对于您的程序,我建议为传递给EXECUTE IMMEDIATE的字符串引入一个局部变量。这些可能是非常棘手的,如果你已经将它们分配给局部变量,你可以使用dbms_output.put_line轻松输出它们。事实上,我在修复你的程序中的问题的同时做到了这一点。如果您希望修改或扩展您的程序,我建议您继续这样做。

无论如何,这是我最终得到的,似乎有效:

create or REPLACE PROCEDURE hostname   
  (host_name in varchar2,user_name in VARCHAR2, pass_word in VARCHAR2,    
  table_space in varchar2,pro_file in varchar2)    
as    
  db_link_name      varchar2(30);
  l_ddl_sql         varchar2(4000);
begin    
  select db_link into db_link_name from all_db_links where host=host_name; 
  l_ddl_sql := 'begin dbms_utility.exec_ddl_statement@'||db_link_name||'(''CREATE     USER '||user_name||' IDENTIFIED BY '||pass_word||'     
    DEFAULT TABLESPACE '||table_space||' PROFILE '|| pro_file||' ACCOUNT UNLOCK''); END;';

  EXECUTE IMMEDIATE l_ddl_sql;

  l_ddl_sql := 'begin dbms_utility.exec_ddl_statement@'||db_link_name||    
    '(''GRANT CONNECT,RESOURCE,EXECUTE_CATALOG_ROLE,Create table,create session,create     view,create sequence,create procedure,create job,create synonym TO '||user_name || '''); END;';

  EXECUTE IMMEDIATE l_ddl_sql;
end;
/