【问题标题】:Must declare the scalar variable "@Name"必须声明标量变量“@Name”
【发布时间】:2016-01-20 20:35:50
【问题描述】:

我有这些包括:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

我的连接字符串是

public partial class Directory : System.Web.UI.Page      
{
    SqlConnection con = new SqlConnection("Data Source=10.4.33.61;Initial Catalog=Bank_Reconciliation;Persist Security Info=True;User ID=****;Password=****");
    protected void Page_Load(object sender, EventArgs e)
    {
    }

我按字符串搜索并在数据网格视图中显示的方法(将搜索按钮命名为btnsearch)是

protected void btnsearch_Click(object sender, EventArgs e)
{
    string str = "select * from Employee where (Name like '%' + @search +       '%') ";
    SqlCommand xp = new SqlCommand(str, con);
    xp.Parameters.Add("@search", SqlDbType.VarChar).Value = txtsearch.Text;

    con.Open();
    xp.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = xp;
    DataSet ds = new DataSet();
    da.Fill(ds,"Name");
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con.Close();
  }
}

我收到以下错误:

必须声明标量变量“@Name”。

为什么会这样,我该如何解决?

【问题讨论】:

  • “@name”是从哪里来的?您的代码中没有“@name”。您向我们展示了正确的代码吗?
  • 是的,它是正确的代码!
  • 代码中的@Name 在哪里?你能粘贴你程序中使用@Name 的部分吗?

标签: asp.net


【解决方案1】:

让 TSQL 只使用 LIKE @search 并在添加参数时处理它可能更容易:

protected void btnsearch_Click(object sender, EventArgs e)
{
    string str = @"SELECT * FROM Employee WHERE Name LIKE @search";
    SqlCommand xp = new SqlCommand(str, con);
    xp.Parameters.AddWithValue("@search", "%" + txtSearch.Text + "%");

    con.Open();
    xp.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = xp;
    DataSet ds = new DataSet();
    da.Fill(ds,"Name");
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con.Close();
}

【讨论】:

  • 我不确定你从哪里得到变量@Name。您能否指定错误出现在哪一行?
【解决方案2】:

将您的按钮点击代码更改为:

protected void btnsearch_Click(object sender, EventArgs e)
{
    string str = "select * from Employee where (Name like '%" + @search +       "%') ";
    SqlCommand xp = new SqlCommand(str, con);
    xp.Parameters.Add("@search", SqlDbType.VarChar).Value = txtsearch.Text;

    con.Open();
    xp.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = xp;
    DataTable dt = new DataTable();
    da.Fill(ds, dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    con.Close();
  }
}

它为like 运算符添加了适当的引号,并且还使用了DataTable 而不是DataSet。您也可以使用 DataSet,但这里似乎不需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多