Professional Documents
Culture Documents
Syntax
Arguments
expression
Is any valid expression [ http://msdn.microsoft.com/en-us/library/ms190286.aspx ] .
data_type
Is the target data type. This includes xml, bigint, and sql_variant. Alias data types cannot be
used. For more information about available data types, see Data Types (Transact-SQL)
[ http://msdn.microsoft.com/en-us/library/ms187752.aspx ] .
length
Is an optional integer that specifies the length of the target data type. The default value is 30.
style
Is an integer expression that specifies how the CONVERT function is to translate expression. If style
is NULL, NULL is returned. The range is determined by data_type. For more information, see the
Remarks section.
Return Types
Remarks
Date and Time Styles
When expression is a date or time data type, style can be one of the values shown in the following table.
Other values are processed as 0. SQL Server supports the date format in Arabic style by using the Kuwaiti
algorithm.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 2 of 19
8 108 - hh:mi:ss
yyyymmdd
14 114 - hh:mi:ss:mmm(24h)
1 These style values return nondeterministic results. Includes all (yy) (without century) styles and a
subset of (yyyy) (with century) styles.
2 The default values (style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121) always return the
century (yyyy).
3 Input when you convert to datetime; output when you convert to character data.
4 Designed for XML use. For conversion from datetime or smalldatetime to character data, the output
format is as described in the previous table.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 3 of 19
5 Hijri is a calendar system with several variations. SQL Server uses the Kuwaiti algorithm.
Important:
By default, SQL Server interprets two-digit years based on a cutoff year of 2049. That is, the two-
digit year 49 is interpreted as 2049 and the two-digit year 50 is interpreted as 1950. Many client
applications, such as those based on Automation objects, use a cutoff year of 2030. SQL Server
provides the two digit year cutoff configuration option that changes the cutoff year used by SQL
Server and allows for the consistent treatment of dates. We recommend specifying four-digit years.
6 Only supported when casting from character data to datetime or smalldatetime. When character data
that represents only date or only time components is cast to the datetime or smalldatetime data types,
the unspecified time component is set to 00:00:00.000, and the unspecified date component is set to
1900-01-01.
7The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have
time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time
zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example:
2006-12-12T23:45:12-08:00
.
When you convert to character data from smalldatetime, the styles that include seconds or milliseconds
show zeros in these positions. You can truncate unwanted date parts when you convert from datetime or
smalldatetime values by using an appropriate char or varchar data type length.
When you convert to datetimeoffset from character data with a style that includes a time, a time zone
offset is appended to the result.
When expression is float or real, style can be one of the values shown in the following table. Other
values are processed as 0.
Value Output
126, 128, 129 Included for legacy reasons and might be deprecated in a future release.
When expression is money or smallmoney, style can be one of the values shown in the following table.
Other values are processed as 0.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 4 of 19
Value Output
0 No commas every three digits to the left of the decimal point, and two digits to the
(default) right of the decimal point; for example, 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the
right of the decimal point; for example, 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the
right of the decimal point; for example, 4235.9819.
xml Styles
When expression is xml, style can be one of the values shown in the following table. Other values are
processed as 0.
Value Output
0 Use default parsing behavior that discards insignificant white space and does not
(default) allow for an internal DTD subset.
Note:
When you convert to the xml data type, SQL Server insignificant white space is
handled differently than in XML 1.0. For more information, see Generating XML
Instances [ http://msdn.microsoft.com/en-us/library/ms190965.aspx ] .
1 Preserve insignificant white space. This style setting sets the default xml:space
handling to behave the same as if xml:space="preserve" has been specified
instead.
If enabled, the server can use the following information that is provided in an
internal DTD subset to perform nonvalidating parse operations.
The parser will ignore external DTD subsets. It also does not evaluate the XML
declaration to see whether the standalone attribute is set yes or no, but instead
parses the XML instance as if it is a stand-alone document.
3 Preserve insignificant white space and enable limited internal DTD subset processing.
Binary Styles
When expression is binary(n), varbinary(n), char(n), or varchar(n), style can be one of the values
shown in the following table. Style values that are not listed in the table return an error.
Value Output
If the data_type is a binary type, the characters 0x are added to the left of the
result.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 5 of 19
1, 2 If the data_type is a binary type, the expression must be a character expression. The
expression must be composed of an even number of hexadecimal digits (0, 1, 2, 3,
4, 5, 6, 7, 8, 9, A, B, C, D, E, F, a, b, c, d, e, f). If the style is set to 1 the characters
0x must be the first two characters in the expression. If the expression contains an
odd number of characters or if any of the characters are invalid an error is raised.
If the length of the converted expression is greater than the length of the data_type
the result will be right truncated.
Fixed length data_types that are larger then the converted result will have zeros
added to the right of the result.
If the data_type is a fix sized character type and the length of the converted result is
less than its length of the data_type; spaces are added to the right of the converted
expression to maintain an even number of hexadecimal digits.
The characters 0x will be added to the left of the converted result for style 1.
Implicit Conversions
Implicit conversions are those conversions that occur without specifying either the CAST or CONVERT
function. Explicit conversions are those conversions that require the CAST or CONVERT function to be
specified. The following illustration shows all explicit and implicit data type conversions that are allowed
for SQL Server system-supplied data types. These include xml, bigint, and sql_variant. There is no
implicit conversion on assignment from the sql_variant data type, but there is implicit conversion to
sql_variant.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 6 of 19
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 7 of 19
When you convert between datetimeoffset and the character types char, varchar, nchar, and
nvarchar the converted time zone offset part should always be double digits for both HH and MM for
example, -08:00.
Note:
Because Unicode data always uses an even number of bytes, use caution when you convert binary
or varbinary to or from Unicode supported data types. For example, the following conversion does
not return a hexadecimal value of 41; it returns 4100:
SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary)
.
Large-value data types exhibit the same implicit and explicit conversion behavior as their smaller
counterparts, specifically the varchar, nvarchar and varbinary data types. However, you should
consider the following guidelines:
For information about how to convert Microsoft .NET Framework common language runtime (CLR) user-
defined types, see Performing Operations on User-defined Types [ http://msdn.microsoft.com/en-
us/library/ms187630.aspx ] . For more information about how to convert from the xml data type, see
Generating XML Instances [ http://msdn.microsoft.com/en-us/library/ms190965.aspx ] .
When you explicitly or implicitly cast the xml data type to a string or binary data type, the content of the
xml data type is serialized based on a set of rules. For information about these rules, see Serialization of
XML Data [ http://msdn.microsoft.com/en-us/library/ms180886.aspx ] . For information on how to cast
from XML to a CLR user-defined type, see Performing Operations on User-defined Types
[ http://msdn.microsoft.com/en-us/library/ms187630.aspx ] . For information about how to convert from
other data types to the xml data type, see Generating XML Instances [ http://msdn.microsoft.com/en-
us/library/ms190965.aspx ] .
Automatic data type conversion is not supported for the text and image data types. You can explicitly
convert text data to character data, and image data to binary or varbinary, but the maximum length is
8000 bytes. If you try an incorrect conversion such as trying to convert a character expression that
includes letters to an int, SQL Server returns an error message.
Output Collation
When the output of CAST or CONVERT is a character string, and the input is a character string, the output
has the same collation and collation label as the input. If the input is not a character string, the output
has the default collation of the database, and a collation label of coercible-default. For more information,
see Collation Precedence (Transact-SQL) [ http://msdn.microsoft.com/en-us/library/ms179886.aspx ] .
To assign a different collation to the output, apply the COLLATE clause to the result expression of the
CAST or CONVERT function. For example:
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 8 of 19
When you convert character or binary expressions (char, nchar, nvarchar, varchar, binary, or
varbinary) to an expression of a different data type, data can be truncated, only partially displayed, or
an error is returned because the result is too short to display. Conversions to char, varchar, nchar,
nvarchar, binary, and varbinary are truncated, except for the conversions shown in the following table.
varchar *
nchar E
nvarchar E
varchar E
nchar E
nvarchar E
* = Result length too short to display. E = Error returned because result length is too short to display.
SQL Server guarantees that only roundtrip conversions, conversions that convert a data type from its
original data type and back again, will yield the same values from version to version. The following
example shows such a roundtrip conversion:
Copy Code
Note:
Do not try to construct binary values and then convert them to a data type of the numeric data
type category. SQL Server does not guarantee that the result of a decimal or numeric data type
conversion to binary will be the same between versions of SQL Server.
The following example shows a resulting expression that is too small to display.
Copy Code
USE AdventureWorks;
GO
SELECT c.FirstName, c.LastName, SUBSTRING(c.Title, 1, 25) AS Title, CAST
(e.SickLeaveHours AS char(1)) AS 'Sick Leave'
FROM HumanResources.Employee e JOIN Person.Contact c ON e.EmployeeID = c.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 9 of 19
ContactID
WHERE NOT EmployeeID >5
Copy Code
(5 row(s) affected)
When you convert data types that differ in decimal places, sometimes the result value is truncated and at
other times it is rounded. The following table shows the behavior.
From To Behavior
When you convert data types in which the target data type has fewer decimal places than the source data
type, the value is rounded. For example, the result of the following conversion is
$10.3497
:
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 10 of 19
SQL Server returns an error message when nonnumeric char, nchar, varchar, or nvarchar data is
converted to int, float, numeric, or decimal. SQL Server also returns an error when an empty string ("
") is converted to numeric or decimal.
Certain datetime Conversions Are Nondeterministic in SQL Server 2005 and Later Versions
In SQL Server 2000, string to date and time conversions are marked as deterministic. However, this is
not true for the styles listed in the following table. For these styles, the conversions depend on the
language settings. SQL Server 2005 and later versions mark these conversions as nondeterministic.
The following table lists the styles for which the string-to-datetime conversion is nondeterministic.
107 109
113 130
Examples
A. Using both CAST and CONVERT
Each example retrieves the name of the product for those products that have a
3
in the first digit of their list price and converts their
ListPrice
to
int
.
Copy Code
-- Use CAST
USE AdventureWorks;
GO
SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS int) LIKE '3%';
GO
-- Use CONVERT.
USE AdventureWorks;
GO
SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice
FROM Production.Product
WHERE CONVERT(int, ListPrice) LIKE '3%';
GO
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 11 of 19
Copy Code
USE AdventureWorks;
GO
SELECT CAST(ROUND(SalesYTD/CommissionPCT, 0) AS int) AS 'Computed'
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO
Computed
------
379753754
346698349
257144242
176493899
281101272
301872549
212623750
298948202
250784119
239246890
101664220
124511336
97688107
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 12 of 19
Copy Code
USE AdventureWorks;
GO
SELECT 'The list price is ' + CAST(ListPrice AS varchar(12)) AS ListPrice
FROM Production.Product
WHERE ListPrice BETWEEN 350.00 AND 400.00;
GO
ListPrice
------------------
(5 row(s) affected)
Copy Code
USE AdventureWorks;
GO
SELECT DISTINCT CAST(p.Name AS char(10)) AS Name, s.UnitPrice
FROM Sales.SalesOrderDetail s JOIN Production.Product p on s.ProductID =
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 13 of 19
p.ProductID
WHERE Name LIKE 'Long-Sleeve Logo Jersey, M';
GO
Name UnitPrice
---------- ---------------------
Long-Sleev 31.2437
Long-Sleev 32.4935
Long-Sleev 49.99
(3 row(s) affected)
Copy Code
USE AdventureWorks;
GO
SELECT p.FirstName, p.LastName, s.SalesYTD, s.SalesPersonID
FROM Person.Contact p JOIN Sales.SalesPerson s ON p.ContactID = s.SalesPersonID
WHERE CAST(CAST(s.SalesYTD AS int) AS char(20)) LIKE '2%';
GO
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 14 of 19
(3 row(s) affected)
The following are several examples that show using CONVERT to convert to typed XML by using the xml
data type [ http://msdn.microsoft.com/en-us/library/ms189887.aspx ] .
This example converts a string with white space, text and markup into typed XML and removes all
insignificant white space (boundary white space between nodes):
Copy Code
CONVERT(XML, '<root><child/></root>')
This example converts a similar string with white space, text and markup into typed XML and preserves
insignificant white space (boundary white space between nodes):
Copy Code
This example casts a string with white space, text, and markup into typed XML:
Copy Code
CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>' AS XML)
The following example displays the current date and time, uses
CAST
to change the current date and time to a character data type, and then uses
CONVERT
display the date and time in the
ISO 8901
format.
Copy Code
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 15 of 19
(1 row(s) affected)
The following example is approximately the opposite of the previous example. The example displays a
date and time as character data, uses
CAST
to change the character data to the
datetime
data type, and then uses
CONVERT
to change the character data to the
datetime
data type.
Copy Code
SELECT
'2006-04-25T15:50:59.997' AS UnconvertedText,
CAST('2006-04-25T15:50:59.997' AS datetime) AS UsingCast,
CONVERT(datetime, '2006-04-25T15:50:59.997', 126) AS
UsingConvertFrom_ISO8601 ;
GO
(1 row(s) affected)
The following examples show the results of converting binary and character data by using different styles.
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 16 of 19
Copy Code
----------------------------
Name
(1 row(s) affected)
Copy Code
--The following example shows how Style 1 can force the result
--to be truncated. The truncation is caused by
--including the characters 0x in the result.
SELECT CONVERT(char(8), 0x4E616d65, 1) AS 'Style 1, binary to character'
------------------------------
0x4E616D
(1 row(s) affected)
Copy Code
--The following example shows that Style 2 does not truncate the
--result because the characters 0x are not included in
--the result.
SELECT CONVERT(char(8), 0x4E616d65, 2) AS 'Style 2, binary to character'
------------------------------
4E616D65
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 17 of 19
(1 row(s) affected)
Copy Code
----------------------------------
0x4E616D6500000000
(1 row(s) affected)
Copy Code
----------------------------------
0x4E616D65
(1 row(s) affected)
Copy Code
----------------------------------
0x4E616D65
(1 row(s) affected)
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 18 of 19
See Also
Reference
SELECT (Transact-SQL) [ http://msdn.microsoft.com/en-us/library/ms189499.aspx ]
System Functions (Transact-SQL) [ http://msdn.microsoft.com/en-us/library/ms187786.aspx ]
Other Resources
Data Type Conversion (Database Engine) [ http://msdn.microsoft.com/en-us/library/ms191530.aspx ]
Writing International Transact-SQL Statements [ http://msdn.microsoft.com/en-
us/library/ms191307.aspx ]
Tags:
Community Content
Looking for quick time conversion from GETDATE()? here's one way...
19:53:56
Tags: getdate()
I tried the following 2 examples and they do not work as this article says. All I want is to take a
number and output it as a hex string, however the examples in this article do not work, so it should
be updated.
--The following example shows how Style 1 can force the result
--to be truncated. The truncation is caused by
--including the characters 0x in the result.
SELECT CONVERT(char(8), 0x4E616d65, 1) AS 'Style 1, binary to character'
------------------------------
0x4E616D
(1 row(s) affected)
--The following example shows that Style 2 does not truncate the
--result because the characters 0x are not included in
--the result.
SELECT CONVERT(char(8), 0x4E616d65, 2) AS 'Style 2, binary to character'
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010
Page 19 of 19
------------------------------
4E616D65
(1 row(s) affected)
----------------
^x
(1 row(s) affected)
[tfl - 13 06 09] Hi - and thanks for your post.You should post questions like this to the
http://www.microsoft.com/communities/newsgroups/en-us/ [ http://www.microsoft.com/commu
Exchange : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.excha
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlse
Windows : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.windo
Windows Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.windo
Virtual Server : http://groups.google.com/group/microsoft.public.virtualserver/topics?ln
Full Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C
Tags:
http://msdn.microsoft.com/en-us/library/ms187928(printer).aspx 19/05/2010