【发布时间】:2014-06-25 12:23:14
【问题描述】:
我正在尝试从 Microsoft SQL Server stored procedure 获取值。我完全需要返回两个值。正如您在下面看到的,其中一个可以通过返回访问,另一个可以通过输出参数访问。我在 WPF(C#) 中运行此代码:
public int InsertCustomerEntranceLogWithOptions(String cardNumber,int buy, int score, out int logID)
{
SqlCommand command = new SqlCommand(
@"
--declare @id int, @logID int
exec @res = Insert_CustomerEntranceLog_WithOptions
@cardNumber, @buy, @score, @logID
--set @logID = @id",
myConnection);
command.CommandType = CommandType.Text;
command.Parameters.Add("@cardNumber", SqlDbType.NVarChar).Value = cardNumber;
command.Parameters.Add("@buy", SqlDbType.Int).Value = buy;
command.Parameters.Add("@score", SqlDbType.Int).Value = score;
command.Parameters.Add("@logID", SqlDbType.Int).Value = 0;
command.Parameters["@logID"].Direction = ParameterDirection.Output;
command.Parameters.Add("@res", SqlDbType.Int).Value = 0;
command.Parameters["@res"].Direction = ParameterDirection.Output;
int res = (int)RunNonQuery(command);
logID = (int)command.Parameters["logID"].Value;
return res;
}
而 RunNonQuery 方法是:
public Object RunNonQuery(SqlCommand command, String returnVariableName = "@res")
{
Object result = null;
if (openConnection())
{
try
{
command.ExecuteNonQuery();
if (returnVariableName.Length != 0)
{
result = command.Parameters[returnVariableName].Value;
//command.Dispose();
}
else
{
//command.Dispose();
return 1;
}
}
catch (TimeoutException ex)
{
//Log
}
catch (Exception ex)
{
Utility.LogExceptionError(ex, 1, 1, 1);
//throw ex;
}
closeConnection();
}
return result;
}
我确定我的RunNonQuery 工作正常。我测试了很多。但是当我InsertCustomerEntranceLogWithOptions 方法时,我得到这个错误:
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in System.Data.dll
Additional information: An SqlParameter with ParameterName 'logID'
is not contained by this SqlParameterCollection.
似乎我没有添加SqlParameter,但正如您所见,插入了LogID。怎么了?
我还删除了 SQL 命令中的 cmets,然后运行它,但我看到了错误。
【问题讨论】:
-
@参数 logID 中缺失 -
天哪!我去测试一下。非常感谢。
-
谢谢大家。你们都帮助我,但我必须选择你的答案之一。但是为你们所有人 +1。
标签: c# sql-server stored-procedures parameters