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

来源:互联网 发布:淘宝客用小黄鸭上货 编辑:程序博客网 时间:2024/05/17 23:10

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

只是语法不同.

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

复制代码
代码
select CAST('123' as int)   -- 123
select CONVERT(int'123')  -- 123

select CAST(123.4 as int)   -- 123
select CONVERT(int123.4)  -- 123 

select CAST('123.4' as int)
select CONVERT(int'123.4')
-- Conversion failed when converting the varchar value '123.4' to data type int.

select CAST('123.4' as decimal)  -- 123
select CONVERT(decimal'123.4'-- 123 


select CAST('123.4' as decimal(9,2))  -- 123.40
select CONVERT(decimal(9,2), '123.4'-- 123.40


declare @Num money
set @Num = 1234.56
select CONVERT(varchar(20), @Num0)  -- 1234.56
select CONVERT(varchar(20), @Num1)  -- 1,234.56
select CONVERT(varchar(20), @Num2)  -- 1234.5600
复制代码

 

 

0 0