获取值存储过程C#

时间:2012-02-08 17:17:39

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

我尝试了各种方法,但没有运气。使用Microsoft Visual Studio和SQL Server 2005 这是c#代码和sql代码

List<SqlParameter>  _params3 = new List<SqlParameter>();
_params3.Add(new SqlParameter("@startdate", txtDateFrom.Text));
_params3.Add(new SqlParameter("@enddate", txtDateTo.Text));
_params3.Add(new SqlParameter("@days", extendedDays));

extendedDays = Convert.ToInt32(DAL.executeStoredProcedureScalar(
                   "Time_Difference_Calc", _params3));

SQL代码:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER PROCEDURE [dbo].[Time_Difference_Calc]
    -- Add the parameters for the stored procedure here
    @startdate datetime,
    @enddate datetime,
    @days int output
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    set @days = (Select RawDays
    - NumWeeks * 2
    + CASE WHEN StartWD = 1 THEN 1 ELSE 0 END
    - CASE WHEN EndWD = 7 THEN 1 ELSE 0 END
    + 1
    AS Result
    FROM
    (SELECT Datepart(dw,@startdate) as StartWD,
    Datepart(dw,@enddate) as EndWD,
    DateDiff(d,@startdate,@enddate) as RawDays,
    DateDiff(wk,@startdate,@enddate) as NumWeeks
    ) A)

    --SET @ReturnValue = @days
    RETURN @days
END

我可以在数据库上运行它就好了。输入2个日期...工作正常我需要..

但每当我在页面中实际运行它时,总是得到

  

System.NullReferenceException:对象引用未设置为   对象的实例。“
  source error:return cmd.ExecuteScalar()。ToString();

感谢任何帮助。差不多这个想法是我只想延长天数等于存储过程返回的任何内容。

5 个答案:

答案 0 :(得分:4)

您需要将@ day的参数的Direction属性设置为ParameterDirection .Output

此外,您必须从@day SqlParamaterValue属性中获取价值

答案 1 :(得分:3)

无法看到调用SQL的实际代码,很难确定,但我很确定你应该为此调用ExecuteNonQuery - 你实际上并没有选择任何返回值,因此null当您的代码尝试检索标量值时引用异常。

如果您的存储过程在SELECT TOP 1 foo FROM bar WHERE baz = @quux;行中有一个部分,那么ExecuteScalar(或您的等效部分)将是合适的。但是,您将该值作为输出参数返回,因此它是非查询。

注意:其他答案对于需要设置参数方向是正确的,但这就是你得到NullReferenceException的原因。

答案 2 :(得分:1)

_params3.Direction = System.Data.ParameterDirection.Output;

执行proc

extendedDays = Convert.ToInt32(_params3.Value);

答案 3 :(得分:1)

更改存储过程以选择值而不是使用参数。然后,您可以继续使用ExecuteScalar

存储过程将是这样的:

ALTER PROCEDURE [dbo].[Time_Difference_Calc]
    -- Add the parameters for the stored procedure here
    @startdate datetime,
    @enddate datetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Select RawDays
    - NumWeeks * 2
    + CASE WHEN StartWD = 1 THEN 1 ELSE 0 END
    - CASE WHEN EndWD = 7 THEN 1 ELSE 0 END
    + 1
    AS Result
    FROM
    (SELECT Datepart(dw,@startdate) as StartWD,
    Datepart(dw,@enddate) as EndWD,
    DateDiff(d,@startdate,@enddate) as RawDays,
    DateDiff(wk,@startdate,@enddate) as NumWeeks
    ) A
END

另一件需要考虑的事情,如果你只是从一个应用程序调用它,那么存储过程就没用了。您不需要SQL Server来执行此计算,并且在代码中更容易。

答案 4 :(得分:0)

SqlParameter daysParameter = new SqlParameter("@days", extendedDays);
    daysParameter .Direction = ParameterDirection.Output;
    _params3.Parameters.Add(daysParameter );

应该做的伎俩