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:
1 CAST as [])23CONVERT[] [])
Example:
1 SELECT 'AB' + 1 --This statement is an error and fails when the varchar value ' AB ' is converted to a data type int. 2 3 SELECT 'AB' + CAST(1 as varchar)--Output AB14 5 SELECT 'AB' + CONVERT(varchar,1)--Output AB1
Both cast and convert can convert time:
1 SELECT CONVERT (DateTime,'2011-07-11') -- Output 2011-07-11 00:00:00.000 2 3 SELECT CAST ('2011-07-11'asDateTime) -- Output 2011-07-11 00:00:00.000
But time-to-string, cast does not convert so many tricks:
1 SELECT CONVERT(varchar,GETDATE(),5)--Output 01-07-132 SELECT CONVERT(varchar,GETDATE(),111)--Output 2013/07/013 SELECT CONVERT(varchar,GETDATE(),1)--Output 07/01/134 5 SELECT CAST(GETDATE() as varchar)--Output 1 9:56pm
SQL Statement conversion Format Function cast, convert difference