[英]sql server data type conversion
I have table with column Percentage varchar(10) Data in that table is 我有带有百分比百分比varchar(10)的表,该表中的数据是
Pecentage
2/10
4/10
6/10
..............
Now I have to convert above percentage to decimal,so now i am doing like this. 现在我必须将上述百分比转换为十进制,所以现在我正在这样做。 select CAST(percentage as decimal) from TabName I am getting following exception Error converting data type varchar to numeric.
从TabName中选择CAST(百分数作为十进制)我得到以下异常将数据类型varchar转换为数值时出错。
I would like to get the results like 0.2,0.4,0.6 我想得到像0.2,0.4,0.6的结果
You cannot convert that varchar format(2/10) to float .You need to get the individual string and then perform the division 您不能将该varchar format(2/10)转换为float。您需要获取单个字符串,然后执行除法
Declare @Sample Table
(Percentage varchar(10))
Insert into @Sample
values
('2/10'),('4/10'),('6/10')
;With CTE (Numerator,denominator)
as
(
Select cast(substring(Percentage,0,charindex('/',percentage))as float),
cast(substring(Percentage,charindex('/',percentage)+1,len(Percentage)) as float)
from @Sample
)
select Numerator/denominator from CTE
Result 结果
(No column name)
0.2
0.4
0.6
Try this 尝试这个
declare @str varchar(20)='2/10'
select @str, CAST(LEFT(@str,CHARINDEX('/',@str)-1) as DECIMAL(10,5))/CAST(RIGHT(@str,LEN(@str)-CHARINDEX('/',@str)) as DECIMAL(10,5))
Declare @Temp Table
(Percentage varchar(10))
Insert into @Temp
values
('2/10'),('4/10'),('6/10')
select
convert(float,SUBSTRING (Percentage ,0 , charindex('/',Percentage)))/
convert(float,SUBSTRING (Percentage ,charindex('/',Percentage)+1,len(Percentage)))
as Result
from @Temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.