C#,sp_executesql和不正确的语法

我正在调用下面的代码。

在线(IDataReader dr = cmd.ExecuteReader()) sql barfs 在’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); } } } 

我看了一下sqlprofiler并注意到以下内容:

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

它用sp_executesql包装我的命令。 我的所有其他sql命令只是执行没有问题。

所以我的问题有两个:1。为什么使用sp_executesql? 我做错了什么?

详细信息:sql2005,c#,vs2005

我注意到你没有将CommandType设置为StoredProcedure ……我不知道这是否是你问题的原因:

 cmd.CommandType = CommandType.StoredProcedure; 

我已经这么做了很多次,我无法计算。

提示在下次抛出exception时触发内存:

在运行应用程序时打开SQL Query Profiler。 当每个命令执行时,它显示生成的SQL并在服务器端运行。 如果生成的SQL以sp_executesql开头,后跟查询,那么它将作为常规查询运行 – 即cmd.CommandType = CommandType.Text ,如果它以exec开头,则可能是作为存储过程运行。 确保为正在尝试运行的查询类型生成正确的SQL。