SQL Statement conversion Format function cast, convert

Source: Internet
Author: User

SQL Statement conversion Format function cast, convert

Both cast and convert are often used. Specially extracted as an article, convenient to find.

Both cast and convert can perform data type conversions. In most cases, the two perform the same function, but the convert also provides some special date format conversions, and cast does not have this function.

Since convert includes all the functions of cast, and convert has a date conversion, why do I need to use cast? In fact, this is for ansi/iso compatibility. Cast is ANSI-compliant, and convert is not.

Grammar:

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

Example:

SELECT ' ab ' + 1    --This statement is an error and fails when the varchar value ' AB ' is converted to a data type int. Select ' AB ' + CAST (1 as varchar)    -output AB1 SELECT ' ab ' + CONVERT (varchar,1)    --Output AB1

Both cast and convert can convert time:

Select CONVERT (datetime, ' 2011-07-11 ')    --Output 2011-07-11 00:00:00.000 SELECT CAST (' 2011-07-11 ' as DateTime)    --Output 2011-07-11 00:00:00.000

But time-to-string, cast does not convert so many tricks:

Select CONVERT (Varchar,getdate (), 5)    --Output 01-07-13 SELECT convert (Varchar,getdate (), 111)  --Output 2013/07/01 Select CONVERT (Varchar,getdate (), 1)    -Output 07/01/13 SELECT CAST (GETDATE () as varchar)    -Output 1 9:56pm

SQL Statement conversion Format function cast, convert

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.