CAST and CONVERT区别

The CAST and CONVERT functions are very similar: Both translate a value from one data type to another. Although their performance is also similar, their syntax and potential usage is slightly different.

Both CAST and CONVERT have a straightforward syntax:

CAST(expression AS new_data_type)

CONVERT(new_data_type, expression, [style])

The expression must already have a data type that is translatable into the new_data_type. For instance, you can't convert an alphanumeric string into an integer.

NOTE

CONVERT has an optional parameter: style. This parameter is allowed only for cases when working with date and time values. SQL Server supports numerous formats for presenting date and time values; the style parameter is used to specify such format.

For example, suppose that we want to retrieve order dates from the sales table. However, we don't care about the time portion; all we need to know is the order date. We could use either CAST or CONVERT to do this, as in the following queries:

SELECT TOP 1 CAST(ord_date AS VARCHAR(12)) FROM sales

or

SELECT TOP 1 CONVERT(VARCHAR(12), ord_date, 109) FROM sales

Both return the same results:

------------ 
Sep 14 1994

In this example, we retrieved a date value in its default format (on my server). In fact, CONVERT(VARCHAR(12), ord_date) would bring the same result. Now, suppose that we need a date value in which month, day, and year are separated by dashes. In such a case, we have no choice but to resort to CONVERT with the style 110:

SELECT TOP 1 CONVERT(VARCHAR, ord_date, 110) FROM sales

Results:

------------ 
09-14-1994

For a complete listing of supported styles for presenting date and time values, refer to SQL Server online documentation.

 

转自:

http://www.informit.com/articles/article.aspx?p=31283&seqNum=4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值