日期时间投射或转换? [英] datetime Cast or Convert?

查看:22
本文介绍了日期时间投射或转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择什么:CastConvert 用于日期时间(Microsoft SQL Server)?

What to choose: Cast or Convert for datetimes (Microsoft SQL Server)?

我看过MSDN规格.乍一看似乎没有区别,除了语法:

I have had a look at the MSDN Specifications. At the first glance it seems there is no difference, except for the syntax:

CAST 的语法:

CAST ( expression AS data_type [ ( length ) ] )

CONVERT 的语法:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

而且 CAST 是 ANSI 标准的,这使得它在不同的数据库平台上更具可移植性.

And CAST is ANSI-standard, which makes it more portable accross different database platforms.

推荐答案

convert 有一个可选参数 style,我建议使用 convert> 而不是 cast.它有助于避免混淆.例如,如果你写 cast('20130302' as date),你会得到什么?3 月 2 日还是 2 月 3 日?

convert has an optional parameter style, and I suggest to use convert instead of cast. It helps to avoid confusion. For example, if you write cast('20130302' as date), what would you get? March 2 or February 3?

此外,如果您在将日期转换为字符串时需要特定格式,则必须使用 convert

Also, if you want specific format when casting to date to string, you bound to use convert

这篇关于日期时间投射或转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆