SQL Server 中的科学数字格式
SELECT
fld AS val,
CONVERT(VARCHAR, FORMAT(fld, 'E2')) AS _2decimal,
CONVERT(VARCHAR, FORMAT(fld, 'E3')) AS _3decimal
结果:
val | _2decimal | _3decimal |
---|---|---|
0.0000007018 | 7.02E-006 | 7.018E-006 |
FORMAT
函数在 SQL Server 上可以很好地完成这项工作(截至 2012 年)。
我正在寻找执行相同工作但使用旧版本 SQL Server 的函数。
谢谢
SELECT
fld AS val,
CONVERT(VARCHAR, FORMAT(fld, 'E2')) AS _2decimal,
CONVERT(VARCHAR, FORMAT(fld, 'E3')) AS _3decimal
Result:
val | _2decimal | _3decimal |
---|---|---|
0.0000007018 | 7.02E-006 | 7.018E-006 |
The FORMAT
function does the job fine with SQL Server (as of 2012).
I'm looking for the functions doing the same job but with older versions of SQL Server.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
LEFT
&右
&ROUND
它可以生成该格式,无需FORMAT
。测试db<>fiddle 此处
Using
LEFT
&RIGHT
&ROUND
it can generate that format withoutFORMAT
.Test on db<>fiddle here
如果需要的话,这一切都可以通过
cross apply
轻松内联。假设
convert(varchar, float, 2)
返回一个精确到小数点后 15 位的值(记录为“始终为 16”,计算前导数字。)由于它是科学记数法,因此将有一个前导数字和小数位是+2
发挥作用的地方。如果该值为负数,则字符串会长一个字符。最棘手的部分是所有舍入行为。负面信号也会带来一个小曲线球。由于四舍五入部分,十四位是最大值。如果您需要 15 个位置,则只需获取
convert(varchar, f, 2)
的原始输出即可。https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=b39ae98e8b301d475941bddec7eaea42
This is all easily inlined if necessary with
cross apply
.The assumptions are that
convert(varchar, float, 2)
returns a value with exactly 15 decimal places (which is documented as "always 16" counting the lead digit.) Since it's scientific notation there will be a leading digit and decimal place which is where the+2
comes into play. If the value is negative then the string is one character longer.The trickiest part is all the rounding behavior. Negative signs throw a small curveball as well. Fourteen places is the maximum because of the rounding portion. If you need 15 places then just grab the original output of
convert(varchar, f, 2)
instead.https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=b39ae98e8b301d475941bddec7eaea42