如何将bigint转换为float

时间:2017-01-07 22:28:01

标签: sql-server

我知道bigint应该隐式转换为float,但似乎不是。

要更新的表列:

[GBUsed] [float] NOT NULL,

该列中的数据示例:

430.5

逻辑:我将2个bigint列相加并除以1024.行中的1个示例 - 我得到:1545

我更新了GBUsed列,它定义为float但不转换。我仍然得到1545。

存储过程:

CREATE PROCEDURE [dbo].[RecalculateBandwidthUsage]
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @RowCount int,
            @Rc int,
            @Message varchar(max),
            @CurrentDateTime datetime

    CREATE TABLE #Temp 
    (
        SwitchID int,
        PortIndex int,
        SwitchIP varchar(50),
        GBUsed bigint 
    )

    SET @CurrentDateTime = GETDATE()

    -- FOR TESTING: 
    BEGIN TRANSACTION
        INSERT #Temp (SwitchID, PortIndex, SwitchIP, GBUsed)
            SELECT 
                c.SwitchID, c.PortIndex,
                s.SwitchIP, 
                SUM ((c.BandwidthIn + c.BandwidthOut) / 1024) AS GBUsed     -- converting to gigabytes
            FROM 
                dbo.BandwidthLogCalculatedTest6 c
            INNER JOIN 
                Switch s ON (c.SwitchID = s.SwitchID)
            WHERE 
                (c.StartDate < DATEADD(HOUR, -1, @CurrentDateTime)  
                AND c.EntryType = 'Second')
            GROUP BY 
                c.SwitchID, c.PortIndex, s.SwitchIP
            ORDER BY 
                c.PortIndex

    SELECT 
        @Rc = @@ERROR,
        @RowCount = @@ROWCOUNT       

    IF @Rc <> 0
    BEGIN 
       SELECT @Message = 'Critical Error - procedure RecalculateBandwidthUsage - on select. Return code: ' + Cast(@Rc as varchar)
       RAISERROR (@Message, 16, 1)
    END

    -- FOR TESTING:
    SELECT 'Temp table '

    SELECT * 
    FROM #temp
    ORDER BY PortIndex

    IF @RowCount > 0
    BEGIN
        -- FOR TESTING:
        SELECT 'Before update '

        SELECT b.SwitchIP, b.SwitchPort, b.GBUsed
        FROM dbo.Bandwidth b
        INNER JOIN #temp t ON (b.SwitchIP = t.SwitchIP AND b.SwitchPort = t.PortIndex )
        ORDER BY b.SwitchPort

        -- Update.
        UPDATE dbo.Bandwidth
        SET GBUsed = CONVERT(float, t.Gbused)
        FROM #Temp t
        WHERE (Bandwidth.SwitchIP = t.SwitchIP AND Bandwidth.SwitchPort = t.PortIndex)

        SELECT @Rc = @@ERROR 

        IF @Rc <> 0
        BEGIN 
            SELECT @Message = 'Critical Error - procedure RecalculateBandwidthUsage - on Bandwidth update. Return code: ' + Cast(@Rc as varchar)
            RAISERROR (@Message, 16, 1)
        END

        -- FOR TESTING:
        SELECT 'After update '

        SELECT b.SwitchIP, b.SwitchPort, b.GBUsed
        FROM dbo.Bandwidth b
        INNER JOIN #temp t ON (b.SwitchIP = t.SwitchIP AND b.SwitchPort = t.PortIndex)
        ORDER BY b.SwitchPort
    END

    ROLLBACK TRANSACTION
END

1 个答案:

答案 0 :(得分:1)

您正在进行整数除法 - 因此,您的结果也将是一个整数(或BIGINT)。

您需要使用此代码才能获得小数值:

SUM ((c.BandwidthIn + c.BandwidthOut) / 1024.0) AS GBUsed  

除以1024.0(而非仅1024)将确保使用小数值