SQL SERVER中强制类型转换cast和convert的区别

在SQL SERVER中,cast和convert函数都可用于类型转换,其功能是相同的,

只是语法不同.

cast一般更容易使用,convert的优点是可以格式化日期和数值.

 1 select CAST('123' as int)   -- 123
 2 select CONVERT(int, '123')  -- 123
 3 
 4 select CAST(123.4 as int)   -- 123
 5 select CONVERT(int, 123.4)  -- 123 
 6 
 7 select CAST('123.4' as int)
 8 select CONVERT(int, '123.4')
 9 -- Conversion failed when converting the varchar value '123.4' to data type int.
10 
11 select CAST('123.4' as decimal)  -- 123
12 select CONVERT(decimal, '123.4') -- 123 
13 
14 
15 select CAST('123.4' as decimal(9,2))  -- 123.40
16 select CONVERT(decimal(9,2), '123.4') -- 123.40
17 
18 
19 
20 declare @Num money
21 set @Num = 1234.56
22 select CONVERT(varchar(20), @Num, 0)  -- 1234.56
23 select CONVERT(varchar(20), @Num, 1)  -- 1,234.56
24 select CONVERT(varchar(20), @Num, 2)  -- 1234.5600

 

posted @ 2017-09-05 10:59  silentmuh  阅读(139)  评论(0编辑  收藏  举报
Live2D