---
title: "存储过程，传入值为sql语句的笔记。"
author: "vortexchoo"
date: "2014-09-26T11:13:28Z"
tags: []
categories: ["数据库"]
slug: "sql"
draft: false
lastmod: "2014-09-26T11:13:28Z"
id: 2122557
url: "https://vortexchoo.iteye.com/blog/2122557"
---

一般的存储过程的传入参数是 具体的值，过程中利用传入的值去计算或是操作。

工作中往往会碰到一些偏向动态的过程操作，例如根据传来的sql语句改变游标。

 

 首先游标中的字段是要确定的，无论传递什么样的sql进来，所查询出来的游标内容是一定的。

如果有了上述的保障，就可以行动了。

首先是创建一个package，这个package种 需要声明 一个cursor Type，用作动态游标。

具体命令如下

 

create or replace package pkg\_systeminfo  
as  
type systeminfo is ref cursor;  --定义一个新的 游标类型  
type record\_type is record(     -- 定义新游标里的内容  
    tid   varchar2(200),  
    tname varchar2(200),  
    rtime date,  
    rid  varchar2(200));  
end;

 

 

接着去写我们的procedure

 

create or replace procedure prc\_systeminfo(sqlstr in varchar2  )

is

  --define  
  sysid varchar2(200);  
  sysname varchar2(200);  
  reg\_time date;  
  reg\_id varchar2(200);  
  reg\_name varchar2(200);  
  usercount number(20);  
  answercount number(20);  
  v\_time varchar2(200);  
  v\_usercount varchar2(200);  
  v\_answercount varchar2(200);  
  n\_flag number(4);  
  **cur pkg\_systeminfo.systeminfo;  --定义游标**  
  **systype pkg\_systeminfo.record\_type; --定义游标容器**

  begin  
    sysid :='';  
    sysname :='';  
    reg\_id:='';  
    reg\_name:='';  
    usercount:=0;  
    answercount:=0;  
    v\_time:='';  
    v\_usercount:='';  
    v\_answercount:='';  
    n\_flag:=0;  
    **open cur for sqlstr;** --打开游标并加入传进的sql  
       loop  
         &lt;&lt;flag&gt;&gt;    --返回点  
         **fetch cur into systype;** --压入数据  
         IF cur%NOTFOUND THEN  
            EXIT;  
            ELSE  
                sysid:=systype.tid;  
                sysname:=systype.tname;  
                reg\_id:=systype.rid;  
                select NVL(count(1),0) into n\_flag from pt\_user\_detail t where t.id = reg\_id;  
                if n\_flag&gt;0 then  
                select NVL(t.name,'') into reg\_name from pt\_user\_detail t where t.id = reg\_id;  
                reg\_time:=systype.rtime;  
                select to\_char(reg\_time ,'yyyy-MM-dd HH:mi:ss') into v\_time from dual;  
                select NVL(count(1),0) into usercount from kasai\_objects\_users\_roles t where t.id\_object = sysid;  
                select to\_char(usercount) into v\_usercount from dual;  
                select NVL(count(1),0) into answercount from common\_surveyuser x,kasai\_objects\_users\_roles y where x.buser=y.id\_user and y.id\_object=sysid;  
                select to\_char(answercount) into v\_answercount from dual;  
                insert into tb\_test\_chunf values(sysname,v\_time,reg\_name,v\_usercount,v\_answercount);  
                else  
                  goto flag;   --不满足条件转向下次循环，类似java的continue  
                end if;  
          end if;  
          end loop;  
          **close cur;**  --关闭  
          commit;  
  end prc\_systeminfo;

 

以上标记黑色加粗字体是比较重要的。