SQLSERVER更优化的判断条件查询方法测试

x1234521 2012-01-04 02:54:23
--更优化的判断条件查询方法测试

--==========create test ===============
create table xjj (col varchar(50))

insert into xjj select 'a'
union all select 'b'
union all select 'c'

declare @p varchar(50)
set @p = ''--change this value (a or b or c or '') to test.
---------------------------------

--==========method 1==========
if @p=''
select * from xjj
else
select * from xjj where col=@p

--==========method 2==========
declare @sql varchar(500)
set @sql='select * from xjj'
if @p<>''
set @sql = @sql+' where col='''+@p+''''
execute(@sql)

--==========method 3==good!!========
select * from xjj where (case when @p<>'' then col else @p end)=@p

--drop table
drop table xjj

留印备忘,顺便散点分!
...全文
160 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
好汉坡 2012-01-05
  • 打赏
  • 举报
回复
用sp_executesql
叶子 2012-01-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 roy_88 的回复:]

SQL code
--method 4 very good--
select * from xjj
where @p='' OR col=@p
[/Quote]
支持这个...
x1234521 2012-01-04
  • 打赏
  • 举报
回复
这个也不错~~
中国风 2012-01-04
  • 打赏
  • 举报
回复
--method 4 very good--
select * from xjj
where @p='' OR col=@p
AcHerat 2012-01-04
  • 打赏
  • 举报
回复
接分,楼主,沙发100!

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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