SQL中常用系統函數
--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)
SQL中常用系統函數