转换函数
1.PARSE Parse是把字符串类型转化为想要的类型,看看和convert和cast的区别SELECT PARSE ('2.111111' AS float ),CAST ('2.111111111111' AS FLOAT) ---------------------- ---------------------- 2.111111 2.111111111111 (1 row (s ) affected ) SELECT PARSE ('19010101' AS DATETIME ),CAST ('19010101' AS DATETIME) Msg 9819, Level 16, State 1, Line 63 Error converting string value '19010101' into data type datetime using culture ''. SELECT PARSE ('1901-01-01' AS DATETIME ),CAST ('1901-01-01' AS DATETIME) ----------------------- ----------------------- 1901-01-01 00:00:00.000 1901-01-01 00:00:00.000 (1 row (s ) affected ) 新功能转日期的时候格式一定要注意,不然转不过去,没有cast好用。2.TRY_CONVERT TRY_CONVERT,如果转化成功返回值,转化不成功返回null,比 convert转化不成功报错,编程更加简单和方便些。 比如:
SELECT CASE WHEN TRY_CONVERT(float, 'test') IS NULL THEN 'Cast failed' ELSE 'Cast succeeded' END AS Result; GO3.TRY_PASSE 和上面的类似,只是不成功返回null。
SELECT TRY_PARSE ('19010101' AS DATETIME ),CAST ('19010101' AS DATETIME) ----------------------- ----------------------- NULL 1901 -01 -01 00 :00 :00.000日期和时间函数 1.DATEFROMPARTS 通过传入年月日参数拼出一个日期,以前使用字符串拼接然后再转化成日期
SELECTDATEFROMPARTS ( 2010, 12, 31 ),CAST ('20101231' AS date) ---------- ---------- 2010-12-31 2010-12-312.DATETIME2FROMPARTS 和上面类似,但是多了时分秒和精度。
SELECT DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 5, 1 ), DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 50, 2 ), DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 500, 3 ); GO --------------------------- --------------------------- --------------------------- 2011-08-15 14:23:44.5 2011 -08 -15 14 :23 :44.50 2011 -08 -15 14 :23 :44.5003.DATATIMEFROMPARTS 和上面基本没有区别,只是没有了精度
SELECT DATETIMEFROMPARTS ( 2010, 12, 31, 23, 59, 59, 0 ) ; ----------------------- 2010-12-31 23:59:59.0004.DATATIMEOFFSETFROMPARTS 相比上面多了时区设置。返回datatimeoffset类型 5.EOMONTH 计算月的最后一天,有了这个就很方便,在编写月报或者什么的时候。
DECLARE @date DATETIME = GETDATE (); SELECT EOMONTH ( @date ) AS 'This Month', EOMONTH ( @date, 1 ) AS 'Next Month',EOMONTH ( @date , -1 ) AS 'Last Month'; GO This Month Next Month Last Month ---------- ---------- ---------- 2016-08-31 2016-09-30 2016-07-316.SMALLDATATIMEFROMPARTS SMALLDATATIME类型在sql server中精度到分钟位置。和上面的函数一样的效果。 逻辑函数 1.CHOOSE 返回列表中的索引值。如果不能传入参数,或者不能解析逗号分隔字符串,所实话没啥用有点鸡肋
SELECT CHOOSE ( 3, 'Manager', 'Director' , 'Developer', 'Tester' ) --------- Developer2.IIF 根据表达式返回值,返回某个值。应该是case when 的简化版
SELECT IIF ( (SELECT COUNT( 1) FROM dbo. t1)>= 1, (SELECT COUNT (1 ) FROM dbo .t1 ), 0 ) ----------- 1字符串函数 1.CONCAT 用处和mysql的concat一样用来连接字符串。
SELECT CONCAT ( 'Happy ', 'Birthday ' , 11 , '/', '25' ) ------------------------------ Happy Birthday 11/252.FORMAT 用来返回指定区域的的文本,比如时间。
DECLARE @d DATETIME = '10/01/2011' ; SELECT FORMAT ( @d , 'D', 'en-US' ) AS 'US English Result' US English Result --------------------------- Saturday, October 1 , 2011