plsql存储过程中,将字段名作为参数,急!

一生所爱qaq 2017-12-01 09:49:58
存储过程如下:
create or replace procedure userstest(v_string,v_column in varchar2, v_cursor out sys_refcursor)
is
begin
if(v_column ='name') then
open v_cursor for select * from users where name=v_string;
elsif (v_column='password') then
open v_cursor for select * from users where name=v_string;
end if;
end;
这里的问题是,没有将where后面的字段名作为参数传过去,而是将字段名做了判断,这样写的话,如果有n个字段的话,就要写n个判断,拜托各位帮忙看看,能不能直接将v_column传给where后面的字段名,就不需要用if判断了,并且能用游标打开。很急,求大佬助攻!
...全文
513 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
一生所爱qaq 2017-12-01
  • 打赏
  • 举报
回复
想请教下一楼的那个动态sql应该怎么写
一生所爱qaq 2017-12-01
  • 打赏
  • 举报
回复
我代码写错个单词,第二个where后面应该是password=v_string,如下: create or replace procedure userstest(v_string,v_column in varchar2, v_cursor out sys_refcursor) is begin if(v_column ='name') then open v_cursor for select * from users where name=v_string; elsif (v_column='password') then open v_cursor for select * from users where password=v_string; end if; end; 你的意思是必须要将v_column和各个字段名比较,不能直接将v_column直接赋值给字段名是吗?我的理想写法是open v_cursor for select * from users where v_column=v_string。
碧水幽幽泉 2017-12-01
  • 打赏
  • 举报
回复
4.最后执行动态SQL语句,用游标去接收查询的结果集
碧水幽幽泉 2017-12-01
  • 打赏
  • 举报
回复
可以做,但是毕竟麻烦,需要编写存储过程,使用动态SQL,给你提供一个思路。
1.执行下面的SQL,循环查询表中的所有列
select * from user_tab_columns where table_name = 'USERS'
2.依次和传进来的v_column比较判断,此时必须要用到if语句。
3.如果步骤2能匹配上,就拼接到动态sql上,否则跳出循环,继续下一次判断。
花开了叫我 2017-12-01
  • 打赏
  • 举报
回复
引号 = /*这里应该有一个引号*/ 引号 引号内部两个引号会被解析为一个 不然会报错
一生所爱qaq 2017-12-01
  • 打赏
  • 举报
回复
谁能帮忙解释下为什么v_sting前面是3个引号吗?
一生所爱qaq 2017-12-01
  • 打赏
  • 举报
回复
因为是从mybatis传值的关系吧,用5楼的方法会报错,就是转义字符的问题,正确的写法一楼在另一个帖子里给我回复了,非常感谢! 下面是一楼给的代码,供参考吧 str:='select * from user2 where '||v_column||'='''||v_string||''''; open v_user for str; 谢谢各位了!
花开了叫我 2017-12-01
  • 打赏
  • 举报
回复
-- 判断传进来字段在表里存在不 SELECT * FROM user_tab_columns WHERE table_name = USERS AND column_name = v_column; 如果存在 执行 下面 v_str := 'select * from users where '||v_column||'='||v_string; OPEN v_cursor for v_str

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧