学习目标:
sql server 中DateName()函数及DatePart()函数
学习内容:
DateName():返回代表指定日期的指定日期部分的字符串
语法:DateName(datepart,date) 返回类型:nvarchar
Datepart():返回代表指定日期的指定日期部分的整数
语法:Datepart(datepart,date) 返回类型:int
datepart输入格式:
日期部分 | 缩写 | 备注 |
---|---|---|
year | yy,yyyy | 年 |
quarter | qq,q | 季度 |
month | mm,m | 月 |
dayofyear | dy,y | 一年中的第几天 |
day | dd,d | 日 |
week | wk,ww | 一年中的第几周 |
weekday | dw | 星期几(日期部分返回对应于星期中的某天的数,例如:Sunday =1,Monday=2以此类推) |
Hour | hh | 小时 |
minute | mi,n | 分钟 |
second | ss,s | 秒 |
millisecond | ms | 毫秒 |
示例代码:
select GETDATE() as '当前日期时间',
DateName(year,GetDate())+'-'+DateName(month,GetDate())+'-'+DateName(day,GetDate()) as '当前日期',
DateName(quarter,GetDate()) as '第几季度',
DateName(week,GetDate()) as '一年中的第几周',
DateName(DAYOFYEAR,GetDate()) as '一年中的第几天',
DateName(year,GetDate()) as '年',
DateName(month,GetDate()) as '月',
DateName(day,GetDate()) as '日',
DateName(hour,GetDate()) as '时',
DateName(minute,GetDate()) as '分',
DateName(second,GetDate()) as '秒',
DateName(MILLISECOND,GetDate()) as '豪秒',
DateName(WEEKDAY,GetDate()) as '星期几'
结果:
select GETDATE() as '当前日期时间',
DatePart(year,GetDate())+'-'+DatePart(month,GetDate())+'-'+DatePart(day,GetDate()) as '当前日期',
DatePart(quarter,GetDate()) as '第几季度',
DatePart(week,GetDate()) as '一年中的第几周',
DatePart(DAYOFYEAR,GetDate()) as '一年中的第几天',
DatePart(year,GetDate()) as '年',
DatePart(month,GetDate()) as '月',
DatePart(day,GetDate()) as '日',
DatePart(hour,GetDate()) as '时',
DatePart(minute,GetDate()) as '分',
DatePart(second,GetDate()) as '秒',
DatePart(MILLISECOND,GetDate()) as '豪秒',
DatePart(WEEKDAY,GetDate()) as '星期几'
注意:
- 对比之后可以发现,Datepart返回int,所以得到的日期是做了运算的结果:DatePart(year,GetDate())+’-’+DatePart(month,GetDate())+’-’+DatePart(day,GetDate())=2021+7+10=2038,经测试’-‘和’+'都是相加
- 在多数SQL SERVER 英文版本中(以及部分繁体版),SELECT DATENAME(month, getdate()) 得到 字符串类型的 January ;
而在简体中文版中:SELECT DATENAME(month, getdate()) 得到的是字符串类型的 ‘01’ ;
而SELECT DATEPART(month,getdate())则在所有版本中都得到的是int类型的 1。 - DateName(WEEKDAY,GetDate())得到的是星期六;DatePart(WEEKDAY,GetDate())得到是7
学习时间:
2021-07-10
总结
附:学习记录,方便查看