Must Declare the Scalar Varialbe RRS feed

  • Question

  • hi everyone ,

    i am posting a similar short code so its easy to view and get the idea in short time , although i search alot on internet but could not able to find the answer .

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data.Sql;
    using System.Data.SqlClient;

    namespace Insert_ADO
        class Program
            static void Main(string[] args)
                String str;
                str = "uahmed";
                SqlConnection thisConnection = new SqlConnection("Data Source=.\\Sqlexpress;Database = dbo;Initial Catalog=dbo;Integrated Security=True;Pooling=False");
                SqlCommand nonqueryCommand = thisConnection.CreateCommand();
                nonqueryCommand.CommandText= "INSERT INTO U2([ID]) VALUES (@str)";


    i get the error @nonqueryCommand.ExecuteNonQuery();
    and error is Must Declare the scalar Variable "@str".
    Sunday, February 14, 2010 2:19 PM

All replies

  • You need to supply the paramter to the command. As it is now, you are saying that the commnd should use @str.
    But there is no param on the command called @str. You need to do something like this:

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "insert into ([u2]) values (@str)";
                SqlParameter p = new SqlParameter();
                p.ParameterName = "@str";
                p.Value = str;

    "Modifying Data with Stored Procedures (ADO.NET)"

    This posting is provided "AS IS" with no warranties.
    Monday, February 15, 2010 8:29 AM
  • Thank you Michael got the concept but 1 small error which i am unable to solve

    when i execute it the same program it give error @ cmd.ExecuteNonQuery() ;
    error is
    Incorrect syntax near '('.
    Tuesday, February 16, 2010 1:55 AM