注册 登录
编程论坛 C# 论坛

c#中sql语句拼接问题

lukebc 发布于 2016-09-01 11:15, 3455 次点击
if request("bh")<>""then
if cond="" then
cond="编号 like '%" & trim(request("bh")) & "%'"
else
cond = cond & " AND 编号 like '%" & trim(request("bh")) & "%'"
end if
end if
if request("ckbh")<>""then
if cond="" then
cond="出库编号 like '%" & trim(request("ckbh")) & "%'"
else
cond = cond & " AND 出库编号 like '%" & trim(request("ckbh")) & "%'"
end if
end if
if request("clmc")<>"" then
If cond="" Then
cond="材料名称 like '%" & trim(request("clmc")) & "%'"
else
cond = cond & "and 材料名称 like '%" & trim(request("clmc")) & "%'"
end if
end if

上面是asp中的拼接方式,我要将它转换成c#中的拼接方式,但是我写的好像不对,谁能帮我改一改
以下是我写的C#的拼接方式
 string sql = "";
            string str = "";
            if (textBox1.Text != "")
            {
                str = "bh like '%" + textBox1.Text + "%'";
            }
            else
            { str = str + "and bh like '%" + textBox1.Text + "%'"; }

            if (textBox1.Text != "")
            {
                str = "mc like '%" + textBox2.Text + "%'";
            }
            else
            { str = str + "and mc like '%" + textBox2.Text + "%'"; }

            if (str != "")
            { sql = "select * from text1 where'" + str + "'"; }
            else { sql = "select * from text1"; }
            label1.Text = sql;

2 回复
#2
沉迷敲代码2016-09-01 11:43
  { sql = "select * from text1 where      '" + str + "'"; }
倒数第三行wher条件没有具体的
#3
Maick2016-09-01 13:36
正确方式是: SELECT * FROM TABLENAME WHERE 1=1 然后后面有的才拼接,可以避免用 AND 的问题 ,..
1