SQL Server数据类型转换函数cast()和convert()详解
https://blog.csdn.net/m0_67401382/article/details/126117592
常用的函数有cast()和convert()。
cast()和convert()函数比较:
(1)cast一般更容易使用,convert的优点是可以格式化日期和数值;
(2)convert一般用于日期和时间类型以及小数之间转换,而cast一般用于小数转数值和字符型;
(3)convert只是显示转换,而cast是强制转换。
select CAST('123' as int) -- 123
select CONVERT(int, '123') -- 123
select CAST(123.4 as int) -- 123
select CONVERT(int, 123.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), @Num, 0) -- 1234.56
select CONVERT(varchar(20), @Num, 1) -- 1,234.56
select CONVERT(varchar(20), @Num, 2) -- 1234.5600
Select CONVERT(varchar(100), GETDATE(), 23): 2006-05-16
1 CONVERT(VARCHAR(19),GETDATE()) 2 CONVERT(VARCHAR(10),GETDATE(),110) 3 CONVERT(VARCHAR(11),GETDATE(),106) 4 CONVERT(VARCHAR(24),GETDATE(),113)