1

I have a method which takes a single string parameter (ID).

I want to use SqlCommand to return a DataTable of results from a query. I'm trying to call a table function from my database (Sql Server) in the query and pass in my ID parameter. The contents of this DataTable will then populate a Combobox. Here's what I have so far...

 public string populateCompanyTransSellingEntityLookUp(string BlockId)
    {
        string _sql = "";  

        SqlCommand _comm = new SqlCommand();
        _comm.Parameters.AddWithValue("(@block_id", BlockId);
        _comm.CommandText = "SELECT [name] FROM dbo.fnGetBlockCompanyWIList(@block_id) ORDER BY [name]; ";
        _comm.Connection = _conn;
        _comm.CommandTimeout = _command_timeout;

        DataTable dt = new DataTable();
        try
        {
            SqlDataReader myReader = _comm.ExecuteReader();
            dt.Load(myReader);
        }
        catch (Exception)
        {

            throw;
        }

        Combo.DataSource = dt;
        return _sql;                
    }

But i'm getting a error, "Must declare scalar variable '@block_id'". why?

4
  • I can not understand where is the problem. Commented Mar 13, 2014 at 15:15
  • _comm.Parameters.AddWithValue("@block_id", BlockId);_comm.CommandText = "SELECT [company_int_name] FROM dbo.fnGetBlockCompanyWIList(@block_id) ORDER BY [company_int_name]; "; Commented Mar 13, 2014 at 15:16
  • 2
    There's no question here Commented Mar 13, 2014 at 15:16
  • What exactly is wrong? Do you get an exception? Is the result set empty? Nobody can help you if you don't ask a question. Commented Mar 13, 2014 at 15:27

1 Answer 1

4

You have an extra bracket here, you should remove it:

 _comm.Parameters.AddWithValue("(@block_id", BlockId);
                               ^^^

And perhaps it doesn't matter but give value to your parameter after you set the CommandText:

_comm.CommandText = "SELECT [name] FROM dbo.fnGetBlockCompanyWIList(@block_id) ORDER BY [name]; ";
_comm.Parameters.AddWithValue("@block_id", BlockId);
Sign up to request clarification or add additional context in comments.

2 Comments

how about _comm.Connection = _conn;, can it be placed after _comm.CommandText?
@V-SHY yes,it shouldn't matter.they are different properties.The important thing is setting the Connection property before try to execute the command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.