现在有用户搜索面板若干项给用户定制搜索,下拉表为可选可不选,我准备在NET中判断Request值非空便加入sqlstr +="
sex=@sex and name=@name.....",因为可能要加入5张表,所以觉得这么弄好象有点,是不是用存储过程呢???第一次做搜索,向高手请教,给个思路也可以。

解决方案 »

  1.   

    参考:
    http://www.cnblogs.com/insus/articles/1999795.html
      

  2.   

    wo 做过几次都是 strsql+=这么拼的
    不过我做的都是 很小的东西
      

  3.   

    存储过程吧。
    或者参数化查询string sql = @"delete from employees where firstname=@fname and lastname=@lname";
    SqlCommand cmdQry = new SqlCommand(sqlqry,conn);
    SqlCommand cmdNon = new SqlCommand(sqlInsert,conn);拼接确实不好。
      

  4.   

    如果使用存储过程,我的问题是:比如定义了若干多个参数@sex bit,@age varchar(3),@height varchar(3)...但是这些参数中有些可能用户并没有选择,所以值是null,就不应该产生比如where age>@age....应该怎么判断如果是空就不生成这个字符串呢?在存储过程里面可以吗?求教
      

  5.   

    动态拼接SQL就可以满足你的需求只拼接where 后面的。如果为空就拼接1=1  不为空就xxx=参数
      

  6.   

    我现在就是这么做的,但是觉得好象挺麻烦,因为还得INNER JON其它表,想在存储过程里面做不知道怎么判断非空。
            string sqlstr ="where ";
            string sex = Request["sex"];
            string h1 = Request["height1"];
            string h2 = Request["height2"];
            ...
            sqlstr+= "sex="+sex;
            if (h1 != null) {
                sqlstr += " and Height>=" + h1;
            }
            if (h2 != null)
            {
                sqlstr += " and Height<=" + h2;
            }
            ....
      

  7.   

    方法里面,将所有的需要拼接的字段都传递进来,在存储过程中拼接动态SQL(在传递条件之前,所有的字段最好做一个replace("'", "''"),防止sql注入)存储过程中,拼接动态sqldeclare @sql nvarchar(4000)
    set @sql='
        select * from ... where 1=1
    '
    假设有以下几个参数:
    @sex int, @name nvarchar(50)if @sex is not null 
    begin
        set @sql = @sql + ' and sex=' + cast(@sex as varchar(5))
    end
    -- @name传递进来之前,最好做一个Trim()的处理
    if @name is not null and len(@name)>0
    begin
        -- 单引号起转义的作用
        set @sql = @sql + ' and name like N''%' + @name + '%'''
    end