To set decimal precision dynamically in SQL Server, wrap the CAST
within a ROUND
. Set maximum needed decimals in CAST
by hard coding, 16
in this example. Put the the @precision
variable into ROUND
.
DECLARE @precison int
select @precison = [ConfigValue] from [TestData] WHERE ConfigName = 'Precision'
select ROUND(CAST( (10.56/10.25)as decimal(18, 16)), @precision)
Working example here (shows Stackoverflow User Rank and Top Percentage):