Converting float to decimal in SQL Server 2008

怎甘沉沦 提交于 2019-12-12 08:27:03

问题


I have a view which needs to return type decimal for columns stored as float.

I can cast each column to decimal as follows:

, CAST(Field1 as decimal) Field1

The problem with this approach, is that decimal defaults to 18,0, which automatically rounds the float columns to 0. I would like to keep a precision of up to 12 decimal places.

However, if I do this:

, CAST(Field1 as decimal(12,12)) Field1

I get a runtime error:

"Arithmetic overflow error converting float to data type numeric"

the float column is defined as length: 8 Precision: 53 in the table. I can not modify anything about the table.

What's the proper way to cast it as decimal w/out losing decimal precision?


回答1:


12, 12 means no digits before the decimal separator: 12 digits in total, 12 of them being after the period.

Use a more appropriate range, say:

DECLARE @var FLOAT = 100
SELECT  CAST(@var as decimal(20,12))

which gives you 8 digits before the separator, or adjust it as needed.



来源:https://stackoverflow.com/questions/4186789/converting-float-to-decimal-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!