Transact-SQL 数据类型转换
Syntax
Syntax for CAST:
CAST ( expression AS data_type [ ( length ) ] )
Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [
Arguments
- expression
-
Is any valid expression.
- data_type
-
Is the target data type. This includes xml, bigint, and sql_variant. Alias data types cannot be used.
- 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
Returns expression translated to data_type.
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. . Beginning with SQL Server 2012, the only styles that are supported when converting from date and time types to datetimeoffset are 0 or 1. All other conversion styles return error 9809.
SQL Server supports the date format in Arabic style by using the Kuwaiti algorithm.
Without century (yy) (1) |
With century (yyyy) |
Standard |
Input/Output (3) |
||
---|---|---|---|---|---|
- |
0 or100(1, 2) |
Default for datetime and smalldatetime |
mon dd yyyy hh:miAM (or PM) |
||
1 |
101 |
U.S. |
1 = mm/dd/yy 101 = mm/dd/yyyy |
||
2 |
102 |
ANSI |
2 = yy.mm.dd 102 = yyyy.mm.dd |
||
3 |
103 |
British/French |
3 = dd/mm/yy 103 = dd/mm/yyyy |
||
4 |
104 |
German |
4 = dd.mm.yy 104 = dd.mm.yyyy |
||
5 |
105 |
Italian |
5 = dd-mm-yy 105 = dd-mm-yyyy |
||
6 |
106 (1) |
- |
6 = dd mon yy 106 = dd mon yyyy |
||
7 |
107 (1) |
- |
7 = Mon dd, yy 107 = Mon dd, yyyy |
||
8 |
108 |
- |
hh:mi:ss |
||
- |
9 or109(1, 2) |
Default + milliseconds |
mon dd yyyy hh:mi:ss:mmmAM (or PM) |
||
10 |
110 |
USA |
10 = mm-dd-yy 110 = mm-dd-yyyy |
||
11 |
111 |
JAPAN |
11 = yy/mm/dd 111 = yyyy/mm/dd |
||
12 |
112 |
ISO |
12 = yymmdd 112 = yyyymmdd |
||
- |
13 or113(1, 2) |
Europe default + milliseconds |
dd mon yyyy hh:mi:ss:mmm(24h) |
||
14 |
114 |
- |
hh:mi:ss:mmm(24h) |
||
- |
20 or120 (2) |
ODBC canonical |
yyyy-mm-dd hh:mi:ss(24h) |
||
- |
21 or121 (2) |
ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset |
yyyy-mm-dd hh:mi:ss.mmm(24h) |
||
- |
126 (4) |
ISO8601 |
yyyy-mm-ddThh:mi:ss.mmm (no spaces)
|
||
- |
127(6, 7) |
ISO8601 with time zone Z. |
yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
|
||
- |
130(1, 2) |
Hijri (5) |
dd mon yyyy hh:mi:ss:mmmAM In this style, mon represents a multi-token Hijri unicode representation of the full month's name. This value will not render correctly on a default US installation of SSMS. |
||
- |
131 (2) |
Hijri (5) |
dd/mm/yyyy hh:mi:ss:mmmAM |
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. . Beginning with SQL Server 2012, the only styles that are supported when converting from date and time types to datetimeoffset are 0 or 1. All other conversion styles return error 9809.
SQL Server supports the date format in Arabic style by using the Kuwaiti algorithm.
Without century (yy) (1) |
With century (yyyy) |
Standard |
Input/Output (3) |
||
---|---|---|---|---|---|
- |
0 or100(1, 2) |
Default for datetime and smalldatetime |
mon dd yyyy hh:miAM (or PM) |
||
1 |
101 |
U.S. |
1 = mm/dd/yy 101 = mm/dd/yyyy |
||
2 |
102 |
ANSI |
2 = yy.mm.dd 102 = yyyy.mm.dd |
||
3 |
103 |
British/French |
3 = dd/mm/yy 103 = dd/mm/yyyy |
||
4 |
104 |
German |
4 = dd.mm.yy 104 = dd.mm.yyyy |
||
5 |
105 |
Italian |
5 = dd-mm-yy 105 = dd-mm-yyyy |
||
6 |
106 (1) |
- |
6 = dd mon yy 106 = dd mon yyyy |
||
7 |
107 (1) |
- |
7 = Mon dd, yy 107 = Mon dd, yyyy |
||
8 |
108 |
- |
hh:mi:ss |
||
- |
9 or109(1, 2) |
Default + milliseconds |
mon dd yyyy hh:mi:ss:mmmAM (or PM) |
||
10 |
110 |
USA |
10 = mm-dd-yy 110 = mm-dd-yyyy |
||
11 |
111 |
JAPAN |
11 = yy/mm/dd 111 = yyyy/mm/dd |
||
12 |
112 |
ISO |
12 = yymmdd 112 = yyyymmdd |
||
- |
13 or113(1, 2) |
Europe default + milliseconds |
dd mon yyyy hh:mi:ss:mmm(24h) |
||
14 |
114 |
- |
hh:mi:ss:mmm(24h) |
||
- |
20 or120 (2) |
ODBC canonical |
yyyy-mm-dd hh:mi:ss(24h) |
||
- |
21 or121 (2) |
ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset |
yyyy-mm-dd hh:mi:ss.mmm(24h) |
||
- |
126 (4) |
ISO8601 |
yyyy-mm-ddThh:mi:ss.mmm (no spaces)
|
||
- |
127(6, 7) |
ISO8601 with time zone Z. |
yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
|
||
- |
130(1, 2) |
Hijri (5) |
dd mon yyyy hh:mi:ss:mmmAM In this style, mon represents a multi-token Hijri unicode representation of the full month's name. This value will not render correctly on a default US installation of SSMS. |
||
- |
131 (2) |
Hijri (5) |
dd/mm/yyyy hh:mi:ss:mmmAM |
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.
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.
float and real Styles
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 |
---|---|
0 (default) |
A maximum of 6 digits. Use in scientific notation, when appropriate. |
1 |
Always 8 digits. Always use in scientific notation. |
2 |
Always 16 digits. Always use in scientific notation. |
126, 128, 129 |
Included for legacy reasons and might be deprecated in a future release. |
money and smallmoney Styles
When expression is money or smallmoney, style can be one of the values shown in the following table. Other values are processed as 0.
Value |
Output |
---|---|
0(default) |
No commas every three digits to the left of the decimal point, and two digits to the 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. |
126 |
Equivalent to style 2 when converting to char(n) or varchar(n) |
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(default) |
Use default parsing behavior that discards insignificant white space and does not allow for an internal DTD subset.
|
||
1 |
Preserve insignificant white space. This style setting sets the default xml:space handling to behave the same as ifxml:space="preserve" has been specified instead. |
||
2 |
Enable limited internal DTD subset processing. 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 |
---|---|
0(default) |
Translates ASCII characters to binary bytes or binary bytes to ASCII characters. Each character or byte is converted 1:1. If the data_type is a binary type, the characters 0x are added to the left of the result. |
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 character type, the expression must be a binary expression. Each binary character is converted into two hexadecimal characters. If the length of the converted expression is greater than the data_type length it will be right truncated. 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.
Tip |
---|
This chart is available as a downloadable PDF file at the Microsoft Download Center. |
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
Large-value data types exhibit the same implicit and explicit conversion behavior as their smaller counterparts, specifically the varchar, nvarcharand varbinary data types. However, you should consider the following guidelines:
Conversion from image to varbinary(max) and vice-versa is an implicit conversion, and so are conversions between text andvarchar(max), and ntext and nvarchar(max).
Conversion from large-value data types, such as varchar(max), to a smaller counterpart data type, such as varchar, is an implicit conversion, but truncation will occur if the large value is too big for the specified length of the smaller data type.
Conversion from varchar, nvarchar, or varbinary to their corresponding large-value data types is performed implicitly.
Conversion from the sql_variant data type to the large-value data types is an explicit conversion.
Large-value data types cannot be converted to the sql_variant data type.
For more information about how to convert from the xml data type, see Create Instances of XML Data.
xml Data Type
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 Define the Serialization of XML Data. For information about how to convert from other data types to the xml data type, see Create Instances of XML Data.
text and image Data Types
Automatic data type conversion is not supported for the text and image data types. You can explicitly convert text data to character data, andimage 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).
To assign a different collation to the output, apply the COLLATE clause to the result expression of the CAST or CONVERT function. For example:
SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS
Truncating and Rounding Results
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.
From data type |
To data type |
Result |
---|---|---|
int, smallint, or tinyint |
char |
* |
varchar |
* |
|
nchar |
E |
|
nvarchar |
E |
|
money, smallmoney, numeric, decimal, float, or real |
char |
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:
DECLARE @myval decimal (5, 2);
SET @myval = 193.57;
SELECT CAST(CAST(@myval AS varbinary(20)) AS decimal(10,5));
-- Or, using CONVERT
SELECT CONVERT(decimal(10,5), CONVERT(varbinary(20), @myval));
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.
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName, SUBSTRING(p.Title, 1, 25) AS Title, CAST(e.SickLeaveHours AS char(1)) AS [Sick Leave]
FROM HumanResources.Employee e JOIN Person.Person p ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID >5;
Here is the result set.
FirstName LastName Title Sick Leave
--------- ------------- ------- --------
Ken Sanchez NULL *
Terri Duffy NULL *
Roberto Tamburello NULL *
Rob Walters NULL *
Gail Erickson Ms. *
(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 |
---|---|---|
numeric |
numeric |
Round |
numeric |
int |
Truncate |
numeric |
money |
Round |
money |
int |
Round |
money |
numeric |
Round |
float |
int |
Truncate |
float |
numeric |
Round Conversion of float values that use scientific notation to decimal or numeric is restricted to values of precision 17 digits only. Any value with precision higher than 17 rounds to zero. |
float |
datetime |
Round |
datetime |
int |
Round |
For example, the result of the following conversion is 10:
SELECT CAST(10.6496 AS int);
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:
SELECT CAST(10.3496847 AS money);
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
The following table lists the styles for which the string-to-datetime conversion is nondeterministic.
All styles below 1001 |
106 |
107 |
109 |
113 |
130 |
1 With the exception of styles 20 and 21
Supplementary Characters (Surrogate Pairs)
Beginning in SQL Server 2012, if you use supplementary character (SC) collations, a CAST operation from nchar or nvarchar to an nchar ornvarchar type of smaller length will not truncate inside a surrogate pair; it truncates before the supplementary character. For example, the following code fragment leaves @x holding just 'ab'. There is not enough space to hold the supplementary character.
DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);
SELECT CAST (@x AS NVARCHAR(3));
When using SC collations the behavior of CONVERT, is analogous to that of CAST.
Compatibility Support
In earlier versions of SQL Server, the default style for CAST and CONVERT operations on time and datetime2 data types is 121 except when either type is used in a computed column expression. For computed columns, the default style is 0. This behavior impacts computed columns when they are created, used in queries involving auto-parameterization, or used in constraint definitions.
Under compatibility level 110 and higher, the default style for CAST and CONVERT operations on time and datetime2 data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.
Upgrading the database to compatibility level 110 and higher will not change user data that has been stored to disk. You must manually correct this data as appropriate. For example, if you used SELECT INTO to create a table from a source that contained a computed column expression described above, the data (using style 0) would be stored rather than the computed column definition itself. You would need to manually update this data to match style 121.
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 toint.
-- Use CAST
USE AdventureWorks2012;
GO
SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS int) LIKE '3%';
GO -- Use CONVERT.
USE AdventureWorks2012;
GO
SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice
FROM Production.Product
WHERE CONVERT(int, ListPrice) LIKE '3%';
GO
B. Using CAST with arithmetic operators
The following example calculates a single column computation (Computed) by dividing the total year-to-date sales (SalesYTD) by the commission percentage (CommissionPCT). This result is converted to an int data type after being rounded to the nearest whole number.
USE AdventureWorks2012;
GO
SELECT CAST(ROUND(SalesYTD/CommissionPCT, 0) AS int) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO
Here is the result set.
Computed
------
379753754
346698349
257144242
176493899
281101272
0
301872549
212623750
298948202
250784119
239246890
101664220
124511336
97688107
(14 row(s) affected)
C. Using CAST to concatenate
The following example concatenates noncharacter, nonbinary expressions by using CAST.
USE AdventureWorks2012;
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
Here is the result set.
ListPrice
------------------
The list price is 357.06
The list price is 364.09
The list price is 364.09
The list price is 364.09
The list price is 364.09
(5 row(s) affected)
D. Using CAST to produce more readable text
The following example uses CAST in the select list to convert the Name column to a char(10) column.
USE AdventureWorks2012;
GO
SELECT DISTINCT CAST(p.Name AS char(10)) AS Name, s.UnitPrice
FROM Sales.SalesOrderDetail AS s
JOIN Production.Product AS p
ON s.ProductID = p.ProductID
WHERE Name LIKE 'Long-Sleeve Logo Jersey, M';
GO
Here is the result set.
Name UnitPrice
---------- ---------------------
Long-Sleev 31.2437
Long-Sleev 32.4935
Long-Sleev 49.99
(3 row(s) affected)
E. Using CAST with the LIKE clause
The following example converts the money column SalesYTD to an int and then to a char(20) column so that it can be used with the LIKEclause.
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName, s.SalesYTD, s.BusinessEntityID
FROM Person.Person AS p
JOIN Sales.SalesPerson AS s
ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS int) AS char(20)) LIKE '2%';
GO
Here is the result set.
FirstName LastName SalesYTD SalesPersonID
---------------- ------------------- ---------------- -------------
Tsvi Reiter 2811012.7151 279
Syed Abbas 219088.8836 288
Rachel Valdez 2241204.0424 289
(3 row(s) affected)
F. Using CONVERT or CAST with typed XML
The following are several examples that show using CONVERT to convert to typed XML by using the XML Data Type and Columns (SQL Server).
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):
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):
CONVERT(XML, '<root> <child/> </root>', 1)
This example casts a string with white space, text, and markup into typed XML:
CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>' AS XML)
For more examples, see Create Instances of XML Data.
G. Using CAST and CONVERT with datetime data
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 usesCONVERT display the date and time in the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601 ;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(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 CASTto change the character data to the datetime data type, and then uses CONVERT to change the character data to the datetime data type.
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
Here is the result set.
UnconvertedText UsingCast UsingConvertFrom_ISO8601
----------------------- ----------------------- ------------------------
2006-04-25T15:50:59.997 2006-04-25 15:50:59.997 2006-04-25 15:50:59.997
(1 row(s) affected)
H. Using CONVERT with binary and character data
The following examples show the results of converting binary and character data by using different styles.
--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(char(8), 0x4E616d65, 0) AS [Style 0, binary to character];
Here is the result set.
Style 0, binary to character
----------------------------
Name
(1 row(s) affected)
--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];
Here is the result set.
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];
Here is the result set.
Style 2, binary to character
------------------------------
4E616D65
(1 row(s) affected)
--Convert the character value 'Name' to a binary value.
SELECT CONVERT(binary(8), 'Name', 0) AS [Style 0, character to binary];
Here is the result set.
Style 0, character to binary
----------------------------------
0x4E616D6500000000
(1 row(s) affected)
SELECT CONVERT(binary(4), '0x4E616D65', 1) AS [Style 1, character to binary];
Here is the result set.
Style 1, character to binary
----------------------------------
0x4E616D65
(1 row(s) affected)
SELECT CONVERT(binary(4), '4E616D65', 2) AS [Style 2, character to binary];
Here is the result set.
Style 2, character to binary
----------------------------------
0x4E616D65
(1 row(s) affected)
I. Converting date and time data types
The following example demonstrates the conversion of date, time, and datetime data types.
DECLARE @d1 date, @t1 time, @dt1 datetime;
SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();
-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [date], CAST (@d1 AS datetime) AS [date as datetime];
-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [time], CAST (@t1 AS datetime) AS [time as datetime];
-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [datetime], CAST (@dt1 AS date) AS [datetime as date], CAST (@dt1 AS time) AS [datetime as time];
Community Additions
Transact-SQL 数据类型转换的更多相关文章
- ORACLE SQL数据类型转换
ORACLE SQL数据类型转换 2019-04-07 22:35:53 广小白 阅读数 429更多 分类专栏: Oracle 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议, ...
- Sql数据类型转换
一.ASCII码值与字符间转换 1.ASCII()与CHAR() ASCII()返回字符表达式最左端字符的ASCII 码值.在ASCII()函数中,纯数字的字符串可不用''括起来,但含其 ...
- sql数据类型转换函数
1.CAST()CAST (<expression> AS <data_ type>[ length ]) 2.CONVERT()CONVERT (<data_ type ...
- MS SQL 数据类型转换
MS SQL 转换数据类型 select cast(列A as int) 列A select convert(int,列A) 列A --转字符串为int select len(ltrim(str('数 ...
- sql 数据类型转换
1.convert(float,endtimepart)——conver(数据类型,字段名称) 2.cast(endtimepart as float)——cast(字段名称 as 数据类型)
- SparkSql 数据类型转换
SparkSql 数据类型转换 1.SparkSql数据类型 1.1数字类型 1.2复杂类型 2.Spark Sql数据类型和Scala数据类型对比 3.Spark Sql数据类型转换案例 3.1获取 ...
- Sql Server函数全解<三>数据类型转换函数和文本图像函数
阅读目录 一:数据类型转换函数 二:文本和图像函数 一:数据类型转换函数 在同时处理不同数据类型的值时,SQL Server一般会自动进行隐士类型转换.对于数据类型相近的值是有效的,比如int和flo ...
- Sql Server函数全解(三)数据类型转换函数和文本图像函数
一:数据类型转换函数 在同时处理不同数据类型的值时,SQL Server一般会自动进行隐士类型转换.对于数据类型相近的值是有效的,比如int和float,但是对于其它数据类型,例如整型和字符类型,隐士 ...
- SQL Server数据类型转换
在SQL Server日常的函数.存储过程和SQL语句中,经常会用到不同数据类型的转换.在SQL Server有两种数据转换类型:一种是显性数据转换:另一种是隐性数据转换.下面分别对这两种数据类型转换 ...
- SQL中数据类型转换
CAST 和 CONVERT 将某种数据类型的表达式显式转换为另一种数据类型.CAST 和 CONVERT 提供相似的功能. 语法 使用 CAST: CAST ( expression AS data ...
随机推荐
- php SESSION 不能跨页面传递
今天想用一个session来实现用户登录判断,也算是对之前session的探究,查了下资料session的运行机制如下: session是服务器端的一种会话机制,当客户端的请求服务器创建一个sessi ...
- 各版本 linux(转)
Linux各种版本下载 ftp://ftp.linuxforum.net/ISO/Redhat7.3/valhalla-i386-disc1.iso ftp://ftp.linuxforum.net/ ...
- iOS几种简单有效的数组排序方法
第一种,利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象 NSComparator cmptr = ^(id obj1 ...
- Solution(项目部署):The server does not support version 3.0 of the J2EE Web module specification
1.错误: 在eclipse中使用run->run on server的时候,选择tomcat6会报错误:The server does not support version 3.0 of t ...
- javascript读取xml的方法【转载】
jquery读取xml文件 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http ...
- JQUERY1.9学习笔记 之内容过滤器(二) 空元素选择器
描述:选择没有子元素(包括文本节点)的标签. jQuery(":empty") 与:parent相反. 例:找出所有为空的元素.(他们没有子元素或文本元素). <!docty ...
- 使用微妙计算PHP脚本执行时间
在PHP中,大多数的时间格式都是以UNIX时间戳表示的,而UNIX时间戳是以s(秒)为最小的计量时间的单位.这对某些应用程序来说不够精确,所以可以调用microtime()返回当前UNIX时间戳和微妙 ...
- GFStableList Adapter
STL中,list的优点是插入.删除性能极佳(时间复杂度只需O(1)即可),而且非常重要的在删除节点后,其迭代器不失效,但list查找却不擅长.map由于其实现的数据结构为rb-tree,因此,其插入 ...
- UIImageView设置为圆形
CGFloat headimageX = self.view.frame.size.width * 0.2; CGFloat headimageY = self.view.frame.size. ...
- 一起学习iOS开发专用词汇,每天记3个,助你变大牛-b
大家做开发最大的问题是什么?英语的问题应该困扰很多的同学的地方,我们提倡科学学习开发中的常用词汇.我们不要求大家有特别好的听.说.写,只要能够记住,能够认识这些常用词汇你以后的开发也将游刃有余.我们的 ...