SQL Server中T-SQL 数据类型转换详解

常用的转换函数是 cast 和 convert,用于把表达式得出的值的类型转换成另一个数据类型,如果转换失败,该函数抛出错误,导致整个事务回滚。在sql server 2012版本中,新增两个容错的转换函数:try_cast 和 try_convert,如果转换操作失败,该函数返回null,不会导致整个事务失败,事务继续执行下去。

注意:对于sql server显式定义的不合法转换,try_cast 和 try_convert 会失败,抛出错误信息:explicit conversion from data type int to date is not allowed.

select try_cast(1 as date)

转换函数是parse 和 try_parse,只用于把字符类型转换为 date/time 和 数字类型,在解析字符时会产生一定的性能消耗。

一,时间类型转换

在把日期/时间类型转换成字符串时,常用的转换函数是convert和cast,convert函数能够在一定程度上显式控制日期/时间的显示格式,而cast对日期/时间类型的显示格式,无法显式控制,我推荐使用另一个功能更强大的函数:format,该函数用于把日期时间类型,按照指定的格式转换成字符串,也可以把数值按照特定的格式输出。

1,常用的转换函数

convert 常用于转换date,datetime 等日期/时间类型,通过指定style参数,能够控制数据显示的格式

cast ( expression as data_type [ ( length ) ] )
convert ( data_type [ ( length ) ] , expression [ , style ] )

常用的style及其显示格式如下:

101 mm/dd/yyyy 110 mm-dd-yyyy 111 yyyy/mm/dd 112 yyyymmdd 120 yyyy-mm-dd hh:mm:ss 121 yyyy-mm-dd hh:mm:sssssss

convert函数的style是数字,记忆起来比较困难,只能按照系统定义的格式来显示,不够灵活。sql server提供更为灵活的转换函数format。

2,format函数,控制日期和时间类型的显示格式

format函数主要用于格式化显示date/time类型和数值类型,参数format用于指定显示的格式,给予用户对格式更自由地控制,culture参数是可选的,用于指定显示的语言,该函数返回值的数据类型是nvarchar,如果格式转换失败,该函数返回null:

format ( value, format [, culture ] ) 

当转换date/time时,在format参数中指定日期/时间显示的格式,通常情况下,日期/时间的格式使用以下关键字符作为占位符:yyyy、mm、dd用来表示:年、月、日,而hh、mm、ss用来表示:时、分、秒,并使用“/”,“-”等作为连接符,例如:

declare @d datetime = getdate(); 
select format( @d, 'dd/mm/yyyy', 'en-us' ) as 'datetime result' 

当转换数值类型时,在参数format中使用#代表一个数字,使用相应的连接符,拼接成数字的格式字符,例如:

format(123456789,'###-##-####') as 'custom number result

二,容错的转换函数

try_cast 和try_convert是容错的转换函数,该函数尝试把表达式的值转换为指定的类型,如果转换成功,返回指定类型的值;如果尝试转换失败,返回null;如果请求把一个类型转换为另一个被显式禁止的数据类型,那么尝试转换失败,抛出错误消息,也就是说,尝试转换能够具有一定的容错,但是,不能做“违法”的转换操作。

try_cast ( expression as data_type [ ( length ) ] )
try_convert ( data_type [ ( length ) ], expression [, style ] )

1,try_cast 返回null

select case when try_cast('test' as float) is null 
    then 'cast failed'
   else 'cast succeeded'
  end as result;

2,try_cast 转换失败,返回error

select try_cast(4 as xml) as result;

错误消息是:explicit conversion from data type int to xml is not allowed.

3,try_cast转换成功

set dateformat mdy;
select try_cast('12/31/2010' as datetime2) as result;

4,try_convert常用于把date/time类型转换为指定格式的字符串

系统预定义style,通过style参数指定最终显示date/time的格式

select try_convert(varchar(8),getdate(),112 ) as result;

三,转换的性能

转换函数的性能是不同的,经过测试,cast 和 convert 的转换性能最好,要比try_cast和try_convert要好一些;而cast的转换性能比convert要好一点。

参考文档:

performance comparison of the sql server parse, cast, convert and try_parse, try_cast, try_convert functions

cast and convert (transact-sql)

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐