读书人

这种存储过程只能这么写吗?该如何解决

发布时间: 2012-04-25 19:32:32 作者: rapoo

这种存储过程只能这么写吗?

Delphi(Pascal) code
with adoquery dobegin  close;  sql.clear;  sql.add('select * from hyxx where flag=0');  if a<>0 then   sql.add('and jf<>0');  if b<>0 then  sql.add('and je<>0');  open;end;

上面的查询语句如果写成存储过程:
SQL code
create procedure hycx@a int,@b intas   if @a<>0 and @b<>0   select * from hyxx where flag=0 and jf<>0 and je<>0  else if @a<>0 and @b=0  select * from hyxx where flag=0 and jf<>0  else if @a=0 and @b<>0  .....


问题:只能这么写吗,有没有更简单的写法(主要是每次条件判断都要重新写一下select那一句,条件如果多了岂不是很麻烦)?

[解决办法]
SQL code
create procedure hycx@a int,@b intas   declare @sql nvarchar(800)  set @sql=N'select * from hyxx where 1=1'  if @a<>0 and @b<>0     set @sql=@sql+N' and flag=0 and jf<>0 and je<>0'  else if @a<>0 and @b=0    set @sql=@sql+N' and flag=0 and jf<>0'  else if @a=0 and @b<>0  .....  exec (@sql) 

读书人网 >.NET

热点推荐