You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL Server中以小数格式获取数字的小数部分

Getting the Decimal Remainder as a Decimal Value in SQL Server

Hey Partha, nice catch with using PARSENAME to extract the decimal part—but I get why you need that value as a proper decimal (like 0.40) instead of just the integer 40. Let's go over two solid ways to get what you need:

The simplest and most efficient approach is to subtract the integer portion of your decimal value from the original number. This avoids string manipulation entirely, which is always better for numeric operations.

DECLARE @Total decimal(7,2) = 1000.40;
DECLARE @Remainder decimal(7,2) = 0;

-- Subtract the integer part (using FLOOR for positive values)
SET @Remainder = @Total - FLOOR(@Total);

SELECT @Remainder; -- Outputs 0.40 as a decimal(7,2)

This method works seamlessly even if @Total is a whole number (like 1000.00)—it'll just return 0.00 instead of a NULL, which is exactly what you want for consistent storage.

Method 2: Adjusting the PARSENAME Result

If you specifically want to stick with PARSENAME, you can convert the extracted integer to a decimal and divide by 10 raised to the number of decimal places (in your case, 2, so divide by 100). Just make sure to handle cases where there's no decimal part to avoid NULLs:

DECLARE @Total decimal(7,2) = 1000.40;
DECLARE @Remainder decimal(7,2) = 0;

-- Convert the PARSENAME result to decimal and scale it down
SET @Remainder = CASE 
                    WHEN PARSENAME(@Total, 1) IS NOT NULL 
                    THEN CAST(PARSENAME(@Total, 1) AS decimal(7,2)) / 100 
                    ELSE 0.00 
                 END;

SELECT @Remainder; -- Outputs 0.40 as a decimal(7,2)

Quick Note

Always prefer Method 1 when working with numeric values—it's faster, less error-prone, and aligns with how SQL Server handles decimal arithmetic natively.

内容的提问来源于stack exchange,提问作者Partha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:40