在SSMS的SQL查询中将千克转换成克

时间:2018-07-12 18:49:46

标签: sql sql-server sql-server-2008 ssms

在下面的代码中,有一个列名为<74006800 69007300 20690073 00206100 20740065 00737400> 的列名,目前在其提取表格中的表以'kg'表示,但我希望通过将kg转换为g << / p>

例如,现在显示2.92千克,我需要将其转换为2920.00克

birthweight

请有人可以更改此SQL以将输出显示为2920.00 g而不是2.92 kg吗?

4 个答案:

答案 0 :(得分:1)

我认为您需要这个:

select cast((cast(rtrim(replace(birthweight, 'kg', '')) as float) * 1000) as varchar(50)) + ' g' birthweight from yourtable

答案 1 :(得分:0)

如果您确实需要,可以创建一个函数来执行此操作。我没有完全测试一下,但应该给您一个想法。

CREATE FUNCTION dbo.converter (@kg decimal)  
RETURNS decimal  
WITH EXECUTE AS CALLER  
AS  
BEGIN  
 DECLARE @g decimal
 SET @g = @kg * 1000

 RETURN(@g);  
END; 

您将在SELECT语句中这样称呼

SELECT CAST(dbo.converter([Your_KG_Column]) as decimal(18,2))

答案 2 :(得分:0)

不知道真实数据可能是什么样子,所以我只是扔了些东西。也许这会有所帮助。

declare @Something table
(
    BirthWeight varchar(10)
)

insert @Something values
('2.92 kg')
, ('3.44 kg')
, ('1.89 kg')

select *
    , convert(varchar(10), convert(int, convert(decimal(7,2), replace(s.BirthWeight, ' kg', '')) * 1000)) + ' g'
from @Something s

答案 3 :(得分:0)

使用CASE,LEFT,PATINDEX和一些CONVERT。

-- Sample data
declare @TestTable table (id int identity(1,1) primary key, WeightField varchar(12));
insert into @TestTable (WeightField) values
 ('3.123459 kg')
,('5.21 kg')
,('9.36 lbs')
,('10.22 KG')
,(NULL)
;

SELECT 
(CASE 
 WHEN Visit.WeightField LIKE '[0-9]%[0-9] kg' -- Only convert the kg when WeightField has a specific format
 THEN CONVERT(VARCHAR(8), CONVERT(DECIMAL(8,2), CONVERT(FLOAT, LEFT(Visit.WeightField, PATINDEX('%[0-9] kg%', Visit.WeightField))) * 1000))+' g'
 WHEN Visit.WeightField IS NULL THEN ''
 ELSE LTRIM(RTRIM(Visit.WeightField))
 END) AS [BirthWeight]
FROM @TestTable AS Visit;