gpt4 book ai didi

C#、sp_executesql 和不正确的语法

转载 作者:太空狗 更新时间:2023-10-29 22:25:13 24 4
gpt4 key购买 nike

我正在调用下面的代码。

(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?2. 我做错了什么?

详情:sql2005、c#、vs2005

最佳答案

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

cmd.CommandType = CommandType.StoredProcedure;

我自己已经做过很多次了,数不过来。

下次抛出异常时触发内存的提示:

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

关于C#、sp_executesql 和不正确的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/376941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com