日期:2014-05-18  浏览次数:20926 次

一个查询语句的动态参数问题
select   *   from   Student   where    
  classid=   @classid   --GradeId=   @GradeId   --SchoolId=   @SchoolId


如何实现:只根据输入的参数查询?
比如参数只有@classid的时候,则GradeId和SchoolId不做为查询条件;
同样参数只有@classid和@GradeId的时候,SchoolId不做为查询条件;


------解决方案--------------------
可将语句用动态SQL写.

用if 判断?
declare @sql as varchar(100)
if @GradeId is null and @SchoolId is null
set @sql = 'select * from Student where classid= ' + @classid
else
if @SchoolId is null and @GradeId is not null
set @sql = 'select * from Student where classid= ' + @classid + ' and GradeId = ' + @GradeId

其中注意参数的类型,如果为字符串型,
set @sql = 'select * from Student where classid= ' ' + @classid + ' '