SQL SUM负值未返回

时间:2011-07-21 13:47:25

标签: asp.net sql-server vb.net tsql

我有一个看起来像这样的SQL查询 -

    CREATE PROCEDURE [dbo].[getMemberFundUnits]
    -- Add the parameters for the stored procedure here
    @member int,
    @fundcode varchar(15),
    @closingdate datetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


    -- Insert statements for procedure here
    SELECT (CASE WHEN SUM(units) IS Null THEN 0 ELSE SUM(units) END) As fundunits
    FROM pe_minv
    WHERE pmi_member = @member AND pmi_fund = @fundcode AND pmi_invested <= @closingdate

END

当我像这样运行存储过程时 -

DECLARE @return_value as float /*int*/

EXEC    @return_value = [dbo].[getFundUnits]
        @member = 9738,
        @fundcode = N'58193',
        @closingdate = N'07/21/2011'

SELECT  'Return Value' = @return_value

我得到两个结果。第一个是正确的-0.0060和第二个@return_value 0

当我从我的代码调用存储过程时也是这种情况,我得到一个0而不是我想要的-0.0060。

这就是我从代码中调用存储过程的方式:

 Dim ds As New DataSet()

    Dim cmd As New SqlCommand("getMemberFundUnits", conn)
    cmd.CommandType = CommandType.StoredProcedure

    Dim p_pm_member As New SqlParameter("@member", SqlDbType.Int)
    p_pm_member.Value = pm_member
    cmd.Parameters.Add(p_pm_member)

    Dim p_fund_code As New SqlParameter("@fundcode", SqlDbType.VarChar)
    p_fund_code.Value = fund_code
    cmd.Parameters.Add(p_fund_code)

    Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
    p_period_closing_date.Value = period_closing_date
    cmd.Parameters.Add(p_period_closing_date)

    Dim da As New SqlDataAdapter(cmd)
    da.Fill(ds)

有没有人有任何想法可能会发生这种情况?

谢谢!

3 个答案:

答案 0 :(得分:3)

DECLARE @return_value as int

您的变量定义为int。 Int不能保存十进制值,因此返回值是四舍五入的。尝试将var声明为float

List of SQL Server data types

答案 1 :(得分:1)

RETURN始终为int,因此它会在存储过程中被截断。 As per MSDN

  

RETURN [integer_expression]

您需要使用浮动的OUTPUT参数:

CREATE PROC [dbo].[getFundUnits]
    @member...,
    @fundcode...',
    @closingdate...,
    @SummedValue float OUTPUT
AS
...
SELECT @SummedValue = (CASE WHEN SUM(nits) IS Null THEN 0 ELSE SUM(units) END) As fundunits
...
GO

你称之为

DECLARE @return_value as float

EXEC    [dbo].[getFundUnits]
        @member = 9738,
        @fundcode = N'58193',
        @closingdate = N'07/21/2011',
        @return_value OUTPUT

SELECT  'Return Value' = @return_value

通常仅对执行状态使用RETURN(如果有的话):有意义的数据是通过输出参数或结果集。我不再使用RETURN ......

答案 2 :(得分:0)

尝试以精确的方式将返回值声明为Decimal。

DECLARE @return_value as decimal(18,4)

另外,为什么要填充数据集以仅返回一列。使用sqldatareader并将值检索为十进制。数据集非常耗费资源。