查询点播资源,要求能按照资源类别名称、资源编号、资源名称、上载日期(区间)查询;
CREATE PROCEDURE uer_select_v_sources @type_name varchar(15)='%',@source_id char(9)='%',@source_name varchar(50)='%', @up_date1 datetime=null,@up_date2  datetime=null                    
ASselect a.source_id as 资源编号,a.source_name as 资源名称,a.source_price as 价格,a.up_date as 上载日期,b.type_name as 资源类别
from tsource as a inner join ttype as b
on a.type_id=b.type_id where b.type_name=@type_name or a.source_id= @source_id or a.source_name=@source_name or  a.up_date between @up_date1  and  @up_date2  
GO
因为我不知道用户真正的需要什么样的功能?所以我设想考虑各种and与or的组合情况,通过定义一个变量来取代and 和or,能否达到呢?怎么做呢?

解决方案 »

  1.   

    set @Operate = 'and'
    declare @s varchar(2000)
    set @s = 'select ... where b.type_name = ''' + @type_name + ''' ' 
        + @Operate + ' a.source_id = ........
    ....
    exec(@s)
      

  2.   

    只有动态Sql能满足你的要求了
      

  3.   

    对的
    使用动态SQL
    你可以判断输入参数中哪些需要放到where子句中,完了之后就execute
      

  4.   

    顶.
    我曾也想过,可弄不出,最后可好写一个判断来确定是add还是or