【问题标题】:Stored Procedures, ExecuteScalar and Parametes存储过程、ExecuteScalar 和参数
【发布时间】:2013-02-19 18:48:26
【问题描述】:

我有一个这样调用的存储过程:

string proc = "SpCreate '00111', 3";

 using (SqlCommand command = new SqlCommand(proc, conn))
 {
       command.CommandType = CommandType.Text;
       command.CommandTimeout = 1000;

       string returnCode = command.ExecuteScalar().ToString();
 }

上面的神工作正常。但是一旦我添加了一个参数,我就会在“SpCreate”附近得到不正确的语法。是什么赋予了? (下面的代码会导致错误。)

string proc = "SpCreate '00111', @myId";

 using (SqlCommand command = new SqlCommand(proc, conn))
 {
       SqlParameter paramName = new SqlParameter("@myId", SqlDbType.Int) { Value = 3 };
       command.Parameters.Add(paramName);

       command.CommandType = CommandType.Text;
       command.CommandTimeout = 1000;

       string returnCode = command.ExecuteScalar().ToString();
 }

【问题讨论】:

  • 您使用的是哪个数据库接口? OleDb 喜欢以 @ 开头的参数,但 SqlDb 更喜欢像 ? 这样的占位符。另外,您是否尝试过使用“exec SpCreate '00111', @myId”?

标签: .net sql stored-procedures sqlparameter


【解决方案1】:

在查看了我自己的一些代码并意识到我有一些错误后编辑了我的答案。

您需要将 CommandType 设置为 StoredProcedure。

编辑:添加示例源代码

 string proc = "SpCreate";

 using (SqlCommand command = new SqlCommand(proc, conn))
 {
       SqlParameter paramName = new SqlParameter("@myId", SqlDbType.Int);
       paramName.Value = 3;
       command.Parameters.Add(paramName);

       command.CommandType = CommandType.StoredProcedure;
       command.CommandTimeout = 1000;

       string returnCode = command.ExecuteScalar().ToString();
 }

【讨论】:

  • 删除/添加@都没有做任何事情。添加 EXEC 导致从 nvarchar 转换为 int 时出错。
  • 你能描述一下你在 proc 中的价值吗? SpCreate 是存储过程的名称吗?如果是,参数是否在存储过程中声明?
  • @chris - 我同意这是一个正确的例子,但这并不完全是你在做什么。我仍然需要你回答我的问题。 “SpCreate”是存储过程的名称吗?如果是,在该存储过程中是否初始化了一个名为“@myId”的参数?
  • 是的 spCreate 是存储过程的名称,myId 是传入的值(出于安全原因,我将代码更改为虚拟文本)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2013-10-10
  • 2011-11-13
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多