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

发布于 2024-11-03 17:10:37 字数 3549 浏览 3 评论 0原文

新手注意!

错误:

<代码> 必须声明标量变量“@param2”。

必须声明标量变量“@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连接。

编辑1:给出完整的代码。::

受保护的字符串 GetSelectionString() { 字符串搜索字符串 = "%"; SearchString = SearchString+ TextBox1.Text.Trim().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();
    }
    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(对象发送者,EventArgs e) { SqlDataSource ds1 = new SqlDataSource(GetConnectionString(), GetSelectionString()); GridView1.DataSource = ds1; GridView1.DataBind(); }

请注意:我将其绑定到 GridView 控件。如果我在查询中对 @param2 的值进行硬编码,则此方法有效。

编辑2:具有不同错误的不同方法: <代码>

tried it this way, 
SqlCommand temp1 = GetSelectionString();
string temp2 = temp1.CommandText.ToString();
SqlDataSource ds1 = new SqlDataSource(GetConnectionString(), temp1.ToString());
GridView1.DataSource = ds1;
GridView1.DataBind();
....getting new error

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

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

Newbie alert!

Error:


Must declare the scalar variable "@param2".

Must declare the scalar variable "@param2"

(twice for two param2's)

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

and

 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 value will be passed by user. I have searched solutions for around 6 hours... and still stuck up with this problem. Any solutions please?

Using VS2008 with MS SQL server 2008 R2 connection.

EDIT1: GIVING THE COMPLETE CODE.::


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();
}

please note: I am binding it to a GridView control. This WORKS if I hardcode the value of the @param2 in the query.

EDIT2: A DIFFERENT APPROACH WITH DIFFERENT ERROR:


tried it this way,
SqlCommand temp1 = GetSelectionString();
string temp2 = temp1.CommandText.ToString();
SqlDataSource ds1 = new SqlDataSource(GetConnectionString(), temp1.ToString());
GridView1.DataSource = ds1;
GridView1.DataBind();

....getting new error

Could not find server 'System' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers

System.Data.SqlClient.SqlException: Could not find server 'System' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不再见 2024-11-10 17:10:37

您需要使用@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;
}

You need to use @param2 as a "stand-alone" parameter - do not pack it into a string!

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");

If you want to search for a string with % at the beginning and end, you need to supply that into the value of @param2

Also: your query might work a lot better if you break up those subselects and use a single SQL statement using JOIN's to join together the tables...

Update: your approach has a very basic flaw: you seem to expect that if you use a parametrized query in the SqlCommand you'll get out the full SQL statement with the parameter value filled in when accessing the SearchAll.CommandText - that is simply not the case - the parameter @param2 will not be substituted with its value!

So basically, you cannot do this the way you're doing it right now - what you need to do is pass back a SqlCommand instance - not just a string! That will never work

Update #2: you need to do something like this:

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();
}

and

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;
}
只有影子陪我不离不弃 2024-11-10 17:10:37

我知道这是一个老问题,但当我试图记住如何完成同样的事情时遇到了它,并且我有一个解决方案。现在我读到了 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;
    }
}

然后,剩下的就是在 SQLDataSource 提供的 GridView 上进行 DataBind。我已经在一些应用程序中使用过它并且效果很好。

安德鲁·科莫

I know this is an old question but I ran across it when trying to remember how to accomplish this same thing and I have a solution. Now that I read Sai Kalyan Akshinthala's most recent answer, I think he might have been hinting at the same thing.

The key is that when you add the parameter to the SQLDataSource's parameter collection, you need to leave the "@" off of the name. The error is stating that it doesn't see a parameter with the correct name to match the one passed in the SQL parameterized string. While the SQL parameter in the string must be named with "@", the matching SQLDataSource parameters should not use it.

Here is my C# code. It is a method used behind a web form that provides a flexible search of an article database.

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;
    }
}

Then, all that remains is to to a DataBind on the GridView that's being supplied by the SQLDataSource. I've used this in a few applications and it works great.

Andrew Comeau

如果没结果 2024-11-10 17:10:37

您将参数连接到查询,这在您的查询中是错误的

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%)");

you concatenating parameter to your query that's wrong in 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%)");
打小就很酷 2024-11-10 17:10:37

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

First your declaration of param2 is useless:
SqlParameter @param2 = new SqlParameter()
If you were to use it - try to make it something a lot more meaningful such as documentName
Second - try removing one of the parameters? does it work?
if you add it a second time does it fail? if so then change the name for the second one and add it as a separate parameter.

微暖i 2024-11-10 17:10:37

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

You, are declaring a Parameter with name param2 and using @param2, so its getting stuck up. Correct it and try.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文