C#, sp_executesql and Incorrect Syntax

血红的双手。 提交于 2019-12-19 19:45:02

问题


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


回答1:


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;

I've done this so many times myself I can't count.

Tip to trigger your memory when this throws exceptions next time:

Have SQL Query Profiler open while you're running your app. When each command executes, it shows the SQL generated and run on the server side. If the SQL generated begins with sp_executesql followed by your query then it's being run as a regular query - i.e. cmd.CommandType = CommandType.Text, if it starts with exec, chances are it's run as a stored proc. Make sure you're getting the correct SQL generated for the type of query you're trying to run.



来源:https://stackoverflow.com/questions/376941/c-sp-executesql-and-incorrect-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!