代码之家  ›  专栏  ›  技术社区  ›  Joel Martinez

查询SQL Server结果集中的小数位数

  •  1
  • Joel Martinez  · 技术社区  · 14 年前

    我有一个表,其中包含类型为的字段 numeric(28,10) . 我想用一个单间距的字体和匹配的小数位数显示记录,以便它们在右对齐时对齐。

    是否有任何方法可以计算出给定结果集中可以找到的最大小数位数,以便在显示每个记录时相应地格式化?

    编辑:对不起,我应该更清楚…如果结果集包含只有3位小数的数字,那么所有的数字应该只有3位小数(用零填充)。

    2 回复  |  直到 14 年前
        1
  •  1
  •   OMG Ponies    14 年前

    单空间字体完全是一个演示问题…

    当我测试时,我不认为你需要正确的校准:

    CREATE TABLE [dbo].[Table_1](
      [num] [numeric](28, 10) NOT NULL
    )
    
    INSERT INTO [example].[dbo].[Table_1] VALUES (1.1234567890);
    INSERT INTO [example].[dbo].[Table_1] VALUES (1.123456789);
    INSERT INTO [example].[dbo].[Table_1] VALUES (1.1234567);
    
    SELECT [num]
      FROM [example].[dbo].[Table_1]
    

    ……返回:

    num
    ---------------
    1.1234567890
    1.1234567890
    1.1234567000
    

    所以问题是——你想做什么却没有给你想要的输出?

        2
  •  0
  •   Tim    14 年前

    您希望在哪里显示结果?查询分析器?在应用程序中?

    你也可以

     a) format the column to have a
        finite number (known in advance) of
        digits to the right of the decimal
        point, truncating at that position;
        this is the typical practice or
    
     b)    read through all of the rows in the
        resultset to determine the value
        with the greatest number of digits
        to the right of the decimal point 
        (casting to string, splitting the
        value using the decimal point as
        delimiter, and getting the length of
        the decimal-fraction string)
    

    如果出于某种原因,选项a)是不可接受的,那么您必须按程序进行,要么是存储过程中的服务器端,要么是客户程序中的客户机端。