问题
I have a strange requirement to round a value in a varchar column in SQL Server 2012. I know it is bad practice to hold numeric values in a varchar.
i.e. the column is a varchar but holds a string representing a number.
I have string values like 834.78330000000005 and 831.06669999999997 and 797.45000000000005 but I want to update these to string values like 834.7833 and 831.0667 and 797.45 (trimming the trailing zeros not too important but desirable).
This seems to be close, are there better options? Should I use round function?
CREATE TABLE [Clinical].[AAAJFJunk]
(
[Call Length] [NVARCHAR](50) NULL
) ON [PRIMARY]
INSERT [Clinical].[AAAJFJunk] ([Call Length] )
VALUES (N'834.78330000000005'),
(N'831.06669999999997'),
(N'797.45000000000005')
GO
UPDATE Clinical.AAAJFJunk
SET [Call Length] =
CAST(CAST([Call Length] AS DECIMAL(11, 4)) AS VARCHAR);
回答1:
Example select to check proposed values:
select
case when ISNULL([Call Length], '') = ''
then ''
else
FORMAT(Cast ( CONVERT(numeric(16,4), CAST([Call Length] AS FLOAT)) as float),'########0.####')
end as val123
from Clinical.AAAJFJunk
Update statement ..
Includes handling of null value (i.e. leaves them untouched)
Includes handling of scientific values with E notation in source string values. e.g. 6.6699999999999995E-2
Includes removing trailing zero on right hand side of number
The Format function is used.
The STR function with a float leaves trailing zeros, so I didn't use that.
The Convert function with a float to a string determines it's own number of decimal places so I wanted to avoid that also !
UPDATE Clinical.AAAJFJunk
SET [Call Length] =
case when ISNULL([Call Length], '') = ''
then '' else
FORMAT(Cast ( CONVERT(numeric(16,4), CAST([Call Length] AS FLOAT)) as float),'########0.####') end
Please note the 0 in the format specifier has a specific meaning.
Please see:
https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
来源:https://stackoverflow.com/questions/54897102/rounding-of-a-value-in-a-varchar-column-in-ms-sql-server-2012