在一个ASP.NET程序中有一个功能是删除用户选中的checkbox代表的记录,我的写法是:
public sub del()
dim strsql as string="delete from db where id in (@id)"
dim id as string=Request("chk_id")
updatedb(strsql,id)
end sub
其中chk_id为客户选中的checkbox控件的值,对应数据库中的id字段,updatedb()为DAL层的更新函数。
这样写当选中的记录数大于一条时就无法删除数据库中的记录。
然后改用循环语句:
public sub del()
dim strsql as string="delete from db where id in (@id)"
dim id as string=Request("chk_id").split(",")
for i=0 to id.length-1
updatedb(strsql,id)
next
end sub
这样写也只能删除第一条记录。设断点后发现问题出在Command.ExecuteNoneQuery语句中,它返回的值为false,但不知道原因。
最后发现不用@id占位符则程序正常,就是将SQL语句写成:"delete from db where id in (" & Request("chk_id") & ")"
请问这是什么原因呢?

解决方案 »

  1.   

    Request("chk_id")的值没问题,都是"2,6,8,10"之类的字符串。
      

  2.   

    sql 中的in 是无法用参数代替的。SqlParameter不是简单的替换。参考:
    http://www.knowdotnet.com/articles/temptables.html
    还可以换个SQL写法
    delete from db where CHARINDEX(id, @id) > 0
      

  3.   

    楼主的是VB代码,我只有C#的代码。这是大致的处理方法:    (1) 动态构造参数化SQL代码: delete from [table] where [id] in (@id0, @id1, @id2)
        (2) 将多个ID逐个加入SqlCommand的Parameters属性中下面是C#代码示例:
    //
    // 参数idsString形如:1,2,3,4,5......
    //
    public int Delete(string idsString)
    {
        int rows = -1;    // 字符串1,2,3,4,5......转整形数组
        string[] idArray = idsString.Split(',');
        int[] ids = new int[idArray.Length];
        for (int i = 0; i < idArray.Length; i++)
        {
            ids[i] = int.Parse(idArray[i]);
        }    if (ids.Length > 0)
        {
            string parmName;
            StringBuilder builder = new StringBuilder();
            SqlParameter[] parms = new SqlParameter[ids.Length];        // 准备SQL参数,形如:@id0, @id1, @id2
            for (int i = 0; i < ids.Length; i++)
            {
                parmName = string.Format("@id{0}", i);
                builder.AppendFormat("{0},", parmName);
                // 参数值送SqlParameter数组
                parms[i] = new SqlParameter(parmName, ids[i]);
            }
            string idParms = builder.ToString().TrimEnd(','); // 删除SQL参数最后多加的“,”        // 构造参数化SQL代码,形如: delete from [table] where [id] in (@id0, @id1, @id2)
            string sql = string.Format("delete from [Categories] where [Id] in ({0})", idParms);
            
            string connectionString = "server=.;database=db;uid=sa;pwd=111"; // 连接字符串
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.Parameters.AddRange(parms);            conn.Open();
                rows = comm.ExecuteNonQuery();            comm.Parameters.Clear();
            }
        }    return rows;
    }
      

  4.   

    发上来你的update()函数来看看。