当我的返回值不为null时,为什么ExecuteScalar()返回null?

时间:2015-09-22 10:14:35

标签: c# sql sql-server stored-procedures null

尝试将SQL程序的结果分配到C#

中的变量

我有一个具有输入和输出参数的过程。 输入inPara的参数采用int outPara的输出参数返回bigint

当我测试过程时,输出参数和返回值都不会读为null。 (因为我让它返回out参数。)

这意味着该过程不是问题,而是我的C#中的内容。

我的连接字符串和所有工作正常。

以下代码:

SqlCommand c = new SqlCommand();

c.CommandText = "ProcedureName";
c.CommandType = CommandType.StoredProcedure;
c.Connection = con; //this works, prev defined

// Something below is the problem:
c.Parameters.Add(new SqlParameter("@inPara", 3));
SqlParameter outer = new SqlParameter("@outPara", SqlDbType.BigInt);
outer.Direction = ParameterDirection.Output;
c.Parameters.Add(outer);

object o = c.ExecuteScalar();

if (o != null) int i = (int) o;

但是o总是会变成 null ,即使它不应该。我错过了什么吗?

根据评论中的建议,我正在显示我的SQL服务器存储过程:

CREATE PROCEDURE MyStoredProcedure (@inPara int, @outPara bigint out )
AS
BEGIN

set @inPara = (Select A.ID from myTable A
INNER JOIN   
(SELECT ROW_NUMBER() OVER(ORDER BY HT_ID DESC) AS 'RN', *
  FROM myTable) B  ON A.ID= B.ID
AND B.RN = outPara)

return @outPara


END
GO

连接的结果是一个包含5行且没有空值的表。 当outPara介于1和5之间时,它会返回@outpara

的值

1 个答案:

答案 0 :(得分:4)

问题在于您返回数据的方式。如果你想使用ExecuteScalar,你不应该返回,而只是简单地选择。

如果您无法更改SP,但代码,解决方案是阅读参数' @ outPara'使用ExecuteNonQuery()。

将SqlCommand对象的UpdatedRowSource属性分配给UpdateRowSource.OutputParameters,以指示将通过输出参数从此存储过程返回数据。

command1.UpdatedRowSource = UpdateRowSource.OutputParameters;
command1.ExecuteNonQuery();

将值读为command1.Parameters["@outPara"].Value;