SQL statement conversion format functions Cast, Convert

Original: https://www.cnblogs.com/kissdodog/p/3165944.html


Both CAST and CONVERT are used frequently. Specially extracted as an article, easy to find.

  Both CAST and CONVERT can perform data type conversion. In most cases, the two perform the same function, the difference is that CONVERT also provides some special date format conversion, and CAST does not have this function.

  Since CONVERT includes all the functions of CAST, and CONVERT can also perform date conversion, why do you need to use CAST? Actually, this is for ANSI/ISO compatibility. CAST is ANSI compatible, while CONVERT is not.

  grammar:

  CAST (expression AS data_type [ (length ) ])

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

 

  Example:

  SELECT  ' AB '  +  1     -- This statement reported an error, failed to convert varchar value 'AB' to data type int.

  SELECT  ' AB '  +  CAST ( 1  AS  varchar )     -- output AB1

  SELECT  ' AB '  +  CONVERT ( varchar , 1 )     -- output AB1

  Both CAST and CONVERT can convert times:

  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 have as many tricks as CONVERT:

  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 07 1 2013 9:56PM

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324659580&siteId=291194637