由于工作需要将之前写过的大量的脚本转为存储过程,手工改费时且容易出错,所以用Python实现出来.代码如下:
# -*- coding: cp936 -*-
#在输入文件中不能有注释,不能直接做查询的select语句
#最好不要有做备份的语句
IGNORE_DROP_TABLE_ERROR=0 #设置是否忽略drop table 产生的error
def itemtox(t_str):
t_sum=set()
while t_str.find('&')!=-1:
t_str=t_str[t_str.find('&')+1:]
if t_str.find('&')==-1:
if t_str.find("'")!=-1:
t_str=t_str[:t_str.find("'")]
if t_str.find("(")!=-1:
t_str=t_str[:t_str.find("(")]
t_sum.add(t_str)
break
else:
t1= t_str.find("'");
t2= t_str.find("(");
t3= t_str.find("&");
if t1!=-1 or t2!=-1:
if t1!=-1 and t2!=-1:
tt=min(t1,min(t2,t3));
if t1!=-1:
tt=min(t1,t3);
if t2!=-1:
tt=min(t2,t3);
t_str=t_str[:tt]
else:
t_sum.add(t_str[:t_str.find('&')])
return t_sum
def onesqltostr(src_a):
for item_xname in xname:
src_list=src_a.split("&"+item_xname)
src_sum=""
i=0;
len_src_list=len(src_list)
for item_src_list in src_list:
if i==len_src_list-1:
break;
i+=1
src_sum+=item_src_list+"'||"+"prc_"+item_xname+"||'"
src_a=src_sum
if src_list[len_src_list-1].strip()!='':
src_a+=src_list[len_src_list-1]
src_a=src_a.replace("||''||",'||')
return "'"+src_a+"'"
filein = open("in.sql","r")
fileout = open("out.sql","w")
src=filein.read();
xname=set()
t=src
t=t.replace('\n'," ")
t=t.replace("'","''")
sqllist=t.split(";");
for item in sqllist:
tt=item.split(" ")
for i in tt:
xname=xname|itemtox(i)
xname=list(xname)
xname.sort(lambda x,y:1 if len(x)<len(y) else -1)
fileout.write("create or replace procedure proc_zbl_tmp\n");
if len(xname)!=0:
fileout.write("(\n");
i=0;
len_xname=len(xname)
for item in xname:
fileout.write("prc_"+item);
i=i+1
if i==len_xname:
fileout.write(" in varchar2\n");
else:
fileout.write(" in varchar2,\n");
if len(xname)!=0:
fileout.write(")\n");
fileout.write("is\n");
fileout.write("sqlstr varchar2(5000);\n");
fileout.write("begin\n");
for item_sqllist in sqllist:
if item_sqllist.strip()=='':
continue;
if IGNORE_DROP_TABLE_ERROR and item_sqllist.lower().find("drop")!=-1:
fileout.write("\nbegin\n");
fileout.write("sqlstr"+":=\n");
fileout.write(onesqltostr(item_sqllist)+";\n");
fileout.write("execute immediate sqlstr;\n");
if IGNORE_DROP_TABLE_ERROR and item_sqllist.lower().find("drop")!=-1:
fileout.write("exception\nwhen others then\n"
"DBMS_OUTPUT.PUT_LINE('Error code ' || SQLCODE || ': ' || SUBSTR(SQLERRM, 1, 64));\n"
"DBMS_OUTPUT.PUT_LINE(sqlstr);\nend;\n\n")
fileout.write("\nend;\n");
filein.close();
fileout.close();