新手请教存储过程中逻辑判断用作参数问题

TheGodOfGods 2010-05-31 04:35:38
有如下存储过程,从表Test中查询nID,strName字段,过滤条件为@strName ,逻辑判断方式(like,=,...)由@nLogicFilter来决定,请教各位大侠,是否有更好办法实现该存储过程?最好不用字符串拼接
[code=SQL]
create procedure dbo.Test1
@nLogicFilter int,
@strName varchar(8000)
AS
BEGIN
IF @nLogicFilter = 1
select nID, strName from dbo.Test where strName like @strName
ELSE IF @nLogicFilter = 2
select nID, strName from dbo.Test where strName = @strName
END
[code=SQL]
...全文
136 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xcliang2004 2010-05-31
  • 打赏
  • 举报
回复
dawugui的方法也要有%%

select nID, strName from dbo.Test where strName like @strName
就可以啦,如果传的参数没有%就是1精确查找如果有%就是模糊查找。
  • 打赏
  • 举报
回复
create procedure dbo.Test1
@nLogicFilter int,
@strName varchar(8000)
AS
BEGIN
select nID, strName from dbo.Test where (@nLogicFilter = 1 and strName like @strName) or (@nLogicFilter = 2 and strName = @strName)
END
顶一个,dawugui厉害
TheGodOfGods 2010-05-31
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 feilniu 的回复:]

引用 3 楼 thegodofgods 的回复:

引用 1 楼 fanzhouqi 的回复:

用 拼接sql 语句来做

要用sql拼接的话,每次调用存储过程语句都会重新编译,跟执行普通sql语句没什么区别,意义也不大啊,没别的更好的办法了?


不光效率低,而且处理不好就为SQL注入留下了隐患。

毓华的方案可以的。
或者干脆像LZ原帖那样用IF...ELSE...……
[/Quote]
我也想用IF...ELSE...不过这种参数可能会有挺多个,所以我决定先用dawugui的方法试试
feilniu 2010-05-31
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 thegodofgods 的回复:]

引用 1 楼 fanzhouqi 的回复:

用 拼接sql 语句来做

要用sql拼接的话,每次调用存储过程语句都会重新编译,跟执行普通sql语句没什么区别,意义也不大啊,没别的更好的办法了?
[/Quote]

不光效率低,而且处理不好就为SQL注入留下了隐患。

毓华的方案可以的。
或者干脆像LZ原帖那样用IF...ELSE...,效率还会高点。
notfoundme 2010-05-31
  • 打赏
  • 举报
回复
顶dawugui
dawugui 2010-05-31
  • 打赏
  • 举报
回复
create procedure dbo.Test1
@nLogicFilter int,
@strName varchar(8000)
AS
BEGIN
select nID, strName from dbo.Test where (@nLogicFilter = 1 and strName like @strName) or (@nLogicFilter = 2 and strName = @strName)
END
TheGodOfGods 2010-05-31
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fanzhouqi 的回复:]

用 拼接sql 语句来做
[/Quote]
要用sql拼接的话,每次调用存储过程语句都会重新编译,跟执行普通sql语句没什么区别,意义也不大啊,没别的更好的办法了?
chuifengde 2010-05-31
  • 打赏
  • 举报
回复
select nID, strName from dbo.Test where strName like case @nLogicFilter  when  1 then @strname else '%'+@strname+'%' end
fanzhouqi 2010-05-31
  • 打赏
  • 举报
回复
用 拼接sql 语句来做

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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