程序员,在sqlserver中,我们常用的数据类型转换函数有cast()和convert()。
1.cast()函数:
用法:
cast(字段名 as 转换的类型),比如:
select cast(188.88 as int) --188,将float类型转换为int类型
select cast('188.88' as decimal) --189,decimal只会保留整数部分
select cast('188.88' as decimal(8,2)) --188.88,将char类型转换为数值类型,8为精度,代表除小数点外,最长为8位;2为小数位数,代表小数点后面保留两位小数。
select cast('188.888888' as decimal(6,3)) --188.89,将varchar类型转换为数值类型,6为精度,代表除小数点外,最长为6位;3为小数位数,代表小数点后面保留3位小数。
select cast('20240526' as date) --2024-05-26 将字符串类型转换为日期类型
select cast('20240526' as datetime) --2024-05-26 00:00:00.000 将字符串转换为日期时间类型
select cast(getdate() as time) --21:47:32.1166667 取当前的时间信息,不保留日期信息
2.convert()函数,convert(目标数据类型,需要转换的值,输出的格式(可选))
select convert(int,28.88) --28,将float类型转换为int类型
select convert(decimal,'28.88') --29,将字符串转换为decimal类型,默认小数位是0
select convert(decimal(6,2),'28.888') --28.89,将字符串转换为decimal类型,小数位保留2位,所以是28.89
select convert(varchar(50),getdate(),120) --2024-05-26 22:01:16,最常用,保留日期时间信息
select convert(varchar(10),getdate(),102) --2024.05.26,只保留日期信息
select convert(varchar(10),getdate(),111) --2024/05/26,只保留日期信息
select convert(varchar(10),getdate(),108) --22:03:18,只保留时间信息
当然,在sqlserver数据库中除了cast()和convert()常用的类型转换函数外,还有parse(),try_parse(),try_cast(),try_convert()。带try前缀的,表示当类型转换失败时,返回NULL值。
select parse('188' as int) --188,将字符串转换为int类型
select try_parse('188.88' as int) --NULL,转换失败则返回NULL
select try_cast('188.88' as decimal) --189,将字符串转换为decimal类型,默认保留0位小数,如果转换失败,返回NULL
select try_cast('188.88' as int) --NULL,转换失败,返回NULL
select try_convert(decimal(5,2),'188.8888') --188.89,将字符串转换为decimal类型,保留2位小数
select try_convert(decimal(5,2),'国内实力派程序员') --NULL,转换失败,返回NULL
我们程序员在做类型转换的时候要注意这3点:
1.类型转换可能会失败,尤其是在转换不兼容的数据类型时(例如,将字符串转换为整数时字符串不是有效的整数格式)。
2.转换函数可能会影响性能,尤其是在处理大量数据时。
3.在进行类型转换时,需要注意数据精度和范围,以避免数据丢失或溢出。