SQL SERVER 2012新增函数之字符串函数FORMAT详解

前言

本文主要介绍的是使用 FORMAT函数将日期/时间和数字值格式化为识别区域设置的字符串。下面话不多说,来看详细的介绍吧。

格式如下:

format(value,format,culture)

第一个参数是要格式化的值,第二个是格式,第三个是区域,比如是中国,还是美国,还是大不列颠等等。

FORMAT 依赖于 .NET Framework公共语言运行时 (CLR) 的存在。

declare @date datetime = ‘2014-01-01’
select FORMAT( @date, ‘d’, ‘en-US’ ) as ‘US English Result’
,FORMAT( @date, ‘d’, ‘en-gb’ ) as ‘Great Britain English Result’
,FORMAT( @date, ‘d’, ‘de-de’ ) as ‘German Result’
,FORMAT( @date, ‘d’, ‘zh-cn’ ) as ‘Simplified Chinese (PRC) Result’;

select FORMAT( @date, ‘D’, ‘en-US’ ) as ‘US English Result’
,FORMAT( @date, ‘D’, ‘en-gb’ ) as ‘Great Britain English Result’
,FORMAT( @date, ‘D’, ‘de-de’ ) as ‘German Result’
,FORMAT( @date, ‘D’, ‘zh-cn’ ) as ‘Chinese (Simplified PRC) Result’;
/*
USEnglish Result Great BritainEnglish Result German Result Simplified Chinese (PRC) Result
————————————————————- ————————————————————
1/1/2014 01/01/2014 01.01.2014 2014/1/1

USEnglish Result Great BritainEnglish Result German Result Chinese (Simplified PRC) Result
————————————————————- ————————————————————
Wednesday,January 01, 2014 01 January 2014 Mittwoch, 1. Januar 2014 2014年1月1日
*/

实例介绍

如果说我想要得到’2014年01月01日的结果,怎么得到呢?

select FORMAT( @date, ‘yyyy年MM月dd日’, ‘zh-cn’) as 当前日期
/*
当前日期
——————–
2014年01月01日
*/

FORMAT除了日期以外,还可以处理一些数字格式和货币格式类型的转换

if object_id(‘[tb]’) is not null drop table [tb]
create table [tb]([id] int,[NumericValue] numeric(3,2))
insert [tb]
select 1,1.26 union all
select 2,2.78 union all
select 3,9.83

select *,
FORMAT([NumericValue], ‘G’, ‘en-us’) as ‘General Format’,
FORMAT([NumericValue], ‘C’, ‘en-us’) as ‘Currency Format’,
FORMAT([NumericValue], ‘G’, ‘de-de’) as ‘General Format’,
FORMAT([NumericValue], ‘C’, ‘de-de’) as ‘Currency Format’
from [tb]
/*
id NumericValue General Format Currency Format General Format Currency Format
——————- —————- —————– —————————————–
1 1.26 1.26 $1.26 1,26 1,26 €
2 2.78 2.78 $2.78 2,78 2,78 €
3 9.83 9.83 $9.83 9,83 9,83 €
*/

指定德国区域性后,小数点变成逗号了,估计做过欧美外包的部分朋友在编程的过程也遇到过类似问题。

总结

本篇文章到此结束,如果您有相关技术方面疑问可以联系我们技术人员远程解决,感谢大家支持本站!


数据运维技术 » SQL SERVER 2012新增函数之字符串函数FORMAT详解