SQL Server中格式良好的数字

时间:2010-12-20 20:27:52

标签: sql-server

如何在Microsoft SQL Server 2005中执行以下操作?

DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT 
WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
ELSE CAST(@PCT AS Varchar) END AS newPct

如果百分比以整数结尾,我试图放弃.0。

2 个答案:

答案 0 :(得分:2)

如果添加CASE关键字

,您将使用的内容
DECLARE @PCT Decimal(4,1)
SET @PCT=3.1
SELECT
    CASE WHEN @PCT = CAST(@PCT AS Int) THEN CAST(CAST(@PCT AS Int) AS Varchar)
    ELSE CAST(@PCT AS Varchar) END AS newPct

答案 1 :(得分:1)

首先尝试施放到浮子上。从float转换为varchar的规则与小数到varchar的规则不同。以下似乎对我有用:

select cast(cast(@PCT as float) as varchar) as 'newPct'