老鬼的博客 来都来啦,那就随便看看吧~
SQL Server datename和datepart的区别
发布于: 2019-09-03 更新于: 2019-09-03 分类于:  阅读次数: 

一:问题描述

1
sqlserver datename和datepart的区别,今天遇到一个sit环境存储过程可以使用datename,到了uat却报了错误,原因是我们使用了datename来获取当前月份,由于不太了解这两个方法,就造成了错误。

二:介绍

1.语法

1
2
3
4
5
Datepart():返回代表指定日期的指定日期部分的整数
语法:Datepart(datepart,date) 返回类型:int

DateName():返回代表指定日期的指定日期部分的字符串
语法:DateName(datepart,date) 返回类型:nvarchar

2.字段描述

日期部分 缩写 备注
year yy,yyyy
quarter q,qq 季度
month m,mm
dayofyear dy,y 一年中的第几天
day dd,d
week wk,ww 一年中的第几周
weekday dw 星期几:日期部分返回对应于星期中的某天的数,例如:Sunday =1
Hour hh 小时
minute mi, n 分钟
second ss, s
millisecond ms 毫秒

3.常用sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 '星期几'
*************感谢您的阅读*************