当前位置: 代码迷 >> Sql Server >> 一个查询语句的动态参数有关问题
  详细解决方案

一个查询语句的动态参数有关问题

热度:95   发布时间:2016-04-27 19:54:23.0
一个查询语句的动态参数问题
select   *   from   Student   where    
  classid=   @classid   --GradeId=   @GradeId   --SchoolId=   @SchoolId


如何实现:只根据输入的参数查询?
[email protected],则GradeId和SchoolId不做为查询条件;
[email protected]@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 + ' '

  相关解决方案