views:

724

answers:

2

Hi,

I'm calling the code below.

On the line (IDataReader dr = cmd.ExecuteReader()) sql barfs with an Incorrect syntax near 'CompanyUpdate'.

   using (SqlCommand cmd = new SqlCommand("CompanyUpdate"))
        {
            cmd.Parameters.Add("@CompanyID",SqlDbType.Int);
            cmd.Parameters.Add("@Description",SqlDbType.VarChar,50);
            cmd.Parameters["@CompanyID"].Value = companyid;
            cmd.Parameters["@Description"].Value = description;

            SqlConnection cn = new SqlConnection("Data Source=[datasource];Initial Catalog=dotNext;User ID=[user];Password=[password];Pooling=True;Application Name=dotNext");
            cn.Open();
            cmd.Connection = cn;
            using (IDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    this.CompanyID = dr.GetInt32(0);
                }
            }
        }

I had a look at sqlprofiler and noticed the following:

exec sp_executesql N'CompanyUpdate',N'@CompanyID int,@Description varchar(50)',@CompanyID=56,@Description='APC'

Its wrapping my command wit a sp_executesql. All my other sql commands are just executed with no issues.

So my question is two fold: 1. Why is it using sp_executesql? 2. What am I doing wrong?

Details: sql2005, c#, vs2005

+5  A: 

I notice that you've not set the CommandType to StoredProcedure... I don't know if that's the cause of your problem or not:

cmd.CommandType = CommandType.StoredProcedure;
BenAlabaster
That is so annoying!! Thank you!
Christian Payne
lol - sometimes it just takes a different set of eyes...
BenAlabaster
Argh, thanks. Why on earth wouldn't it error out if you add parameters to a SqlCommand and don't set it to StoredProcedure...
jcollum
Because you can parameterize queries too, so it's not a requirement that it be a stored procedure in order to be able to add parameters...
BenAlabaster
+1 I just did the same stupid thing of forgetting to set that.
Kevin
A: 

Thank you!! Been going blind wondering what's going on.... now I know.

Jonathan C.