存储过程中如何根据参数是否为空执行不同的select??

singit6 2009-07-20 11:11:31
假设表T1,其中有A1,A2,D1,D2等多个字段,A1,A2为varchar型,D1,D2为日期型。
传来四个参数,@A1,@A2,@D1,@D2,如果为空,则不必理会;如果不为空,则加到条件子句中。

@A1,@D1不空为,那么。
要执行select * from t1 where a1=@A1 and d1>=@D1
如果@A2,@D2不为空,则执行 select * from t1 where A2=@A2 and d2<=@D2
当然,这四个参数是不固定有没有的,可能这次查询没有,下次查询就有了。
也可能同时都为空,那么就执行select * from t1即可。
请问这样的存储过程应该怎么写?
谢谢。
...全文
219 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
SQL77 2009-07-20
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 singit6 的回复:]
各位,我不太明白
where A1=isnull(@A1,A1)
and  A2=isnull(@A2,A2)
and D1=isnull(@D1,D1)
and D2=isnull(@D2,D2)
这是什么意思,如果没有这个参数该条件就作废吗?
我是在想能不能像以下ASP代码一样的效果:
dim sql="where 1=1 "
if a1 <>"" then sql=sql & "and a1="& a1
if a2 <>"" then sql=sql & "and a2="& a2
if d1 <>"" then sql=sql & "and d1>="& d1
if d2 <>"" then sql=sql & "and d2 <="& d2
请问以上语句跟我设想的效果一样吗?


[/Quote]
不是作废,是恒成立!!!!and D2=isnull(@D2,D2)
如果为空D2=D2
singit6 2009-07-20
  • 打赏
  • 举报
回复
各位,我不太明白
where A1=isnull(@A1,A1)
and A2=isnull(@A2,A2)
and D1=isnull(@D1,D1)
and D2=isnull(@D2,D2)
这是什么意思,如果没有这个参数该条件就作废吗?
我是在想能不能像以下ASP代码一样的效果:
dim sql="where 1=1 "
if a1<>"" then sql=sql & "and a1="& a1
if a2<>"" then sql=sql & "and a2="& a2
if d1<>"" then sql=sql & "and d1>="& d1
if d2<>"" then sql=sql & "and d2<="& d2
请问以上语句跟我设想的效果一样吗?

sdhdy 2009-07-20
  • 打赏
  • 举报
回复
网速太慢,竟然和3楼不谋而合。
sdhdy 2009-07-20
  • 打赏
  • 举报
回复
--这样应该就没问题了。
select * from tb
where A1=isnull(@A1,A1)
and A2=isnull(@A2,A2)
and D1=isnull(@D1,D1)
and D2=isnull(@D2,D2)
chenjialin2000 2009-07-20
  • 打赏
  • 举报
回复
if (@A1 is not null or @D1 is not null or @A2 is not null or @D2 is not null )
begin
if (@A1 is not null and @D1 is not null )
select * from t1 where a1=@A1 and d1>=@D1
if (@A2 is not null and @D2 is not null )
select * from t1 where A2=@A2 and d2 <=@D2
end
else
select * from t1
百年树人 2009-07-20
  • 打赏
  • 举报
回复
select 
*
from
T1
where
A1=isnull(@A1,A1)
and
A2=isnull(@A2,A2)
and
D1=isnull(@D1,D1)
and
D2=isnull(@D2,D2)
--小F-- 2009-07-20
  • 打赏
  • 举报
回复
if exists .....is null
else
.....
SQL77 2009-07-20
  • 打赏
  • 举报
回复
用IF判断!!还没太懂楼主意思
singit6 2009-07-20
  • 打赏
  • 举报
回复
哦,那就是说跟作废的效果一样啊。明白了。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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