转换为float将返回的结果限制为仅7个字符

时间:2015-04-16 05:04:29

标签: sql sql-server floating-point

我有一个查询,它解析一个字符串并将其转换为float,然后再添加结果。

这是代码:

[XXX]      = (SELECT CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),0,3))AS float) + (CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),3,6))AS float)/60))

如果我一直向下突出显示选择结果

13.9503166666667

但是当我使用整个代码时,就像:

INSERT INTO TblCurrent_TEMP(XXX)
SELECT [XXX]      = (SELECT CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),0,3))AS float) + (CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),3,6))AS float)/60))

这样返回。

13.9503

我期待这样的结果

13.950316

我的查询有问题

我的表结构是

XXX varchar(500)

2 个答案:

答案 0 :(得分:1)

试试这个......   将xxx的数据类型更改为numeric(10,6)

    create table TblCurrent_TEMP
    (
        XXX numeric(10,6)
    )

    insert into TblCurrent_TEMP
    select (SELECT CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),0,3))AS float) + (CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),3,6))AS float)/60))


     select * from TblCurrent_TEMP

答案 1 :(得分:1)

您可以使用STR功能

  

返回从数字数据转换的字符数据。

类似

DECLARE @TABLE TABLE(
        XXX VARCHAR(500)
)
INSERT INTO @TABLE (XXX)
SELECT XXX = LTRIM(STR((SELECT CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),0,3))AS float) + (CAST((SUBSTRING (SUBSTRING('351856040522039,241111;1G,150403155719,A,1357.0198N,12136.8786E,0.0,345,1.0,01004000;', 42, 9),3,6))AS float)/60)), 500, 10))

SELECT  *
FROM    @TABLE

来自CAST and Convert您会注意到从FLOAT到VARCHAR的转换是隐含的,并且有一节提及截断和舍入结果

此外,还有以下结果的战利品

SELECT  CAST(CAST(5.5 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.55 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.555 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.5555 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.55555 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.555555 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.5555555 AS FLOAT) AS VARCHAR(10)),
        CAST(CAST(5.55555555 AS FLOAT) AS VARCHAR(10))

SELECT  STR(CAST(5.5 AS FLOAT),10,10),
        STR(CAST(5.55 AS FLOAT),10,10),
        STR(CAST(5.555 AS FLOAT),10,10),
        STR(CAST(5.5555 AS FLOAT),10,10),
        STR(CAST(5.55555 AS FLOAT),10,10),
        STR(CAST(5.555555 AS FLOAT),10,10),
        STR(CAST(5.5555555 AS FLOAT),10,10),
        STR(CAST(5.55555555 AS FLOAT),10,10)

您应该将值存储在更合适的类型中,除非这是一个属性表,假设存储多种类型。