必须声明标量变量@param问题

时间:2011-04-29 05:29:29

标签: asp.net sql-server ado.net sqlcommand

新手警报!

错误:

Must declare the scalar variable "@param2".

Must declare the scalar variable "@param2" (两次param2的两次)

protected void Button1_Click(object sender, EventArgs e)
{
   SqlDataSource ds1 = new SqlDataSource(GetConnectionString(), GetSelectionString());
   GridView1.DataSource = ds1;
   GridView1.DataBind();
}

 protected string GetSelectionString()
    {
        string SearchString = TextBox1.Text.ToString();
        if (RadioButtonList1.SelectedValue == "ALL")
        {
            SqlParameter @param2 = new SqlParameter();
            SqlCommand SearchAll = new SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Id IN (SELECT Document_Id FROM Search_Index WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id FROM Tags WHERE (Tag_Name LIKE '%'+@param2+'%'))))) UNION SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 WHERE (Document_Name LIKE '%'+@param2+'%')");
           SearchAll.Parameters.AddWithValue("@param2", SearchString.ToString());
            return (string)SearchAll.CommandText.ToString();
        }

TextBox1值将由用户传递。我已经搜索了大约6个小时的解决方案......并且仍然坚持这个问题。有什么解决方案吗?

将VS2008与MS SQL Server 2008 R2连接一起使用。

EDIT1:提供完整的代码。::

protected string GetSelectionString() { string SearchString = "%"; SearchString = SearchString+ TextBox1.Text.Trim().ToString(); SearchString =SearchString+ "%";

    if (RadioButtonList1.SelectedValue == "ALL")
    {
        SqlParameter @param2 = new SqlParameter();
        SqlCommand SearchAll = new SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Id IN (SELECT Document_Id FROM Search_Index WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id FROM Tags WHERE (Tag_Name LIKE @param2))))) UNION SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 WHERE (Document_Name LIKE @param2)");
        SearchAll.Parameters.AddWithValue("@param2", SearchString.ToString());
        return (string)SearchAll.CommandText.ToString();
    }
    if (RadioButtonList1.SelectedValue == "FILENAMES")
    {
        SqlParameter param2 = new SqlParameter();

        SqlCommand SearchFileName = new SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Name LIKE @param2)");
        SearchFileName.Parameters.AddWithValue("@param2", SearchString.ToString());
        return (string)SearchFileName.CommandText.ToString();
    }

protected void Button1_Click(object sender, EventArgs e) { SqlDataSource ds1 = new SqlDataSource(GetConnectionString(), GetSelectionString()); GridView1.DataSource = ds1; GridView1.DataBind(); }

if (RadioButtonList1.SelectedValue == "ALL") { SqlParameter @param2 = new SqlParameter(); SqlCommand SearchAll = new SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Id IN (SELECT Document_Id FROM Search_Index WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id FROM Tags WHERE (Tag_Name LIKE @param2))))) UNION SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 WHERE (Document_Name LIKE @param2)"); SearchAll.Parameters.AddWithValue("@param2", SearchString.ToString()); return (string)SearchAll.CommandText.ToString(); } if (RadioButtonList1.SelectedValue == "FILENAMES") { SqlParameter param2 = new SqlParameter(); SqlCommand SearchFileName = new SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Name LIKE @param2)"); SearchFileName.Parameters.AddWithValue("@param2", SearchString.ToString()); return (string)SearchFileName.CommandText.ToString(); }

请注意:我将它绑定到GridView控件。如果我在查询中对@ param2的值进行硬编码,这就行了。

EDIT2:一种具有不同错误的不同方法:

....得到新的错误

无法在sys.servers中找到服务器“System”。验证是否指定了正确的服务器名称。如有必要,执行存储过程sp_addlinkedserver以将服务器添加到sys.servers

System.Data.SqlClient.SqlException:在sys.servers中找不到服务器“System”。验证是否指定了正确的服务器名称。如有必要,执行存储过程sp_addlinkedserver以将服务器添加到sys.servers。

5 个答案:

答案 0 :(得分:4)

您需要使用@param2作为“独立”参数 - 将其打包成字符串!

SqlCommand SearchAll = new SqlCommand(
   "SELECT Document_Name, Document_Summary FROM Document_Details 
    WHERE (Document_Id IN 
       (SELECT Document_Id FROM Search_Index 
        WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id 
                          FROM Tags 
                          WHERE Tag_Name LIKE @param2)))) 
    UNION 
    SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 
    WHERE Document_Name LIKE @param2");

如果您想在开头和结尾搜索包含%的字符串,则需要将其提供为@param2

的值

另外:如果您拆分这些子选择并使用JOIN的单个SQL语句将表连接在一起,您的查询可能会运行得更好......

更新:您的方法有一个非常基本的缺陷:您似乎期望如果在SqlCommand中使用参数化查询,您将使用参数获取完整的SQL语句访问SearchAll.CommandText时填写的值 - 根本不是这种情况 - 参数@param2替换为其值!

所以基本上,你不能像现在这样做 - 你需要做的就是传回一个SqlCommand实例 - 而不是只是一个字符串!这将从不工作

更新#2:您需要执行以下操作:

protected void Button1_Click(object sender, EventArgs e)
{
   // grab search string from web UI
   string searchString = "%" + TextBox1.Text.Trim() + "%";

   // get connection string
   string connectionString = GetConnectionString();

   SqlDataSource ds1 = new SqlDataSource(connectionString);

   // get the SqlCommand to do your SELECT
   ds1.SelectCommand = GetSelectCommand(connectionString, searchString);

   GridView1.DataSource = ds1;
   GridView1.DataBind();
}

protected SqlCommand GetSelectCommand(string connectionString, string searchValue)
{
   // define query string - could be simplified!
   string queryStmt = "SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Id IN (SELECT Document_Id FROM Search_Index WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id FROM Tags WHERE Tag_Name LIKE @param2)))) UNION SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 WHERE Document_Name LIKE @param2";

   // set up a SqlCommand based on the query string and the connection string passed in       
   SqlCommand cmd = new SqlCommand(queryStmt, connectionString);

   // define parameter
   cmd.Parameters.Add("@param2", SqlDbType.VarChar, 100);

   // set value for parameter
   cmd.Parameters["@param2"].Value = searchValue;

   // pass back SqlCommand to fill the data source
   return cmd;
}

答案 1 :(得分:3)

我知道这是一个老问题,但是当我试图记住如何完成同样的事情并且我有一个解决方案时,我遇到了它。现在我读了Sai Kalyan Akshinthala的最新答案,我想他可能一直在暗示同样的事情。

关键是当你将参数添加到SQLDataSource的参数集合时,你需要保留名称的“@”。该错误表明它没有看到具有正确名称的参数以匹配SQL参数化字符串中传递的参数。虽然字符串中的SQL参数必须以“@”命名,但匹配的SQLDataSource参数不应使用它。

这是我的C#代码。它是一种在Web表单后面使用的方法,可以灵活地搜索文章数据库。

protected void CreateArticleSearch()
{
    // Declare the base query and start the WHERE clause.
    string articleQuery = "SELECT DisplayTitle, Summary, CreateDate, ArticleID FROM Articles ";
    string whereClause = "WHERE ";

    try
    {
        // Important, clear the parameters first.
        Articles.SelectParameters.Clear();

        // Test the field to see if there's anything there.
        if (textTitle.Text.Length > 0)
        {
            // If there is a value, add to the WHERE clause and add a parameter.
            whereClause += "DisplayTitle LIKE @ArticleTitle ";
            Articles.SelectParameters.Add("ArticleTitle", "%" + textTitle.Text + "%");
        }

        // Do the same for each subsequent field except test to see if the
        // WHERE clause already holds something and add AND as necessary.
        if (textSummary.Text.Length > 0)
        {
            if (whereClause == "WHERE ")
                whereClause += "Summary LIKE @ArticleSummary ";
            else
                whereClause += "AND Summary LIKE @ArticleSummary ";

            Articles.SelectParameters.Add("ArticleSummary", "%" + textSummary.Text + "%");
        }

        // Test WHERE clause to see if it contains anything.
        // Add it to the base query if it does.
        if (whereClause.Length > 6)
            articleQuery += whereClause;

        // Specify the command type for the SQLDataSource and attach the query.
        Articles.SelectCommandType = SqlDataSourceCommandType.Text;
        Articles.SelectCommand = articleQuery;

    }
    catch
    {
        throw;
    }
}

然后,剩下的就是GridView上由DataData提供的DataBind。我在一些应用程序中使用过它,效果很好。

Andrew Comeau

答案 2 :(得分:2)

you concatenating parameter to your query您的查询错误

SqlCommand("SELECT Document_Name, Document_Summary FROM Document_Details WHERE (Document_Id IN (SELECT Document_Id FROM Search_Index WHERE (Tag_Id IN (SELECT DISTINCT Tag_Id FROM Tags WHERE (Tag_Name LIKE %@param2%))))) UNION SELECT Document_Name, Document_Summary FROM Document_Details AS Document_Details_1 WHERE (Document_Name LIKE %@param2%)");

答案 3 :(得分:1)

首先你的param2声明是无用的: SqlParameter @ param2 = new SqlParameter() 如果您要使用它 - 尝试使它更有意义,例如documentName 第二 - 尝试删除其中一个参数?它有用吗? 如果你第二次添加它会失败吗?如果是,则更改第二个名称,并将其添加为单独的参数。

答案 4 :(得分:0)

您正在声明名称为param2且使用@param2的参数,因此它会被卡住。纠正它并尝试。