--1 CONVERT(数据类型,表达式),CAST( 表达式 AS 数据类型) 转变数据类型
--将数字转化为字符串
SELECT CONVERT(varchar(2),12)+CONVERT(varchar(2),10) --+为连接符
--同下
SELECT CAST(12 AS varchar(2))+CAST(10 AS varchar(2))
--将字符串转化为整型
SELECT CONVERT(int,‘12‘)+CONVERT(int,‘10‘ ) --+为加号符
--同下
SELECT CAST(‘12‘ AS int)+CAST(‘10‘ AS int)
--将日期转化为字符型,其中的日期格式如下:
Without century (yy) (1) | With century (yyyy) | Standard | Input/Output (3) |
---|---|---|---|
- | 0 or 100 (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 or 109 (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 or 113 (1,2) | Europe default + milliseconds | dd mon yyyy hh:mi:ss:mmm(24h) |
14 | 114 | - | hh:mi:ss:mmm(24h) |
- | 20 or 120 (2) | ODBC canonical | yyyy-mm-dd hh:mi:ss(24h) |
- | 21 or 121 (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) Note: When the value for milliseconds (mmm) is 0, the millisecond value is not displayed. For example, the value ‘2012-11-07T18:26:20.000 is displayed as ‘2012-11-07T18:26:20‘. |
- | 127(6, 7) | ISO8601 with time zone Z. | yyyy-mm-ddThh:mi:ss.mmmZ (no spaces) Note: When the value for milliseconds (mmm) is 0, the milliseconds value is not displayed. For example, the value ‘2012-11-07T18:26:20.000 is displayed as ‘2012-11-07T18:26:20‘. |
- | 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 does not render correctly on a default US installation of SSMS. |
- | 131 (2) | Hijri (5) | dd/mm/yyyy hh:mi:ss:mmmAM |
SELECT CONVERT(varchar(10),GETDATE(),126)
SELECT CONVERT(varchar(10),GETDATE(),100)
--同下
SELECT CAST(GETDATE() AS varchar(10) )
--此外还可以转换为以下格式:
--2 CURRENT_USER 返回当前用户的名字
SELECT CURRENT_USER
--3 DATALENFTH 返回用于指定表达式的字节数
SELECT DATAlENGTH(‘中国A‘)
SELECT DATALENGTH(‘123433‘)
--4 HOST_NAME 返回当前用户所登录的计算机名字
SELECT HOST_NAME() --计算机名字
SELECT HOST_ID() --计算机ID
--5 SYSTEM_USER 返回当前所登陆的用户名称
SELECT SYSTEM_USER
--6 USER_NAME 从给定的用户ID 返回用户名
SELECT USER_NAME(1)