sql取指定时间段内的所有月份

时间:2023-03-08 15:39:29
sql取指定时间段内的所有月份
declare @begin datetime,@end datetime
set @begin='2017-01-01'
set @end='2019-03-04' declare @months int
set @months=DATEDIFF(month,@begin,@end)
select convert(varchar(7),DATEADD(month,number,@begin) ,120) AS 月份
from master.dbo.spt_values
where type='p' AND number<=@months

查询2017-01-01到2019-03-04之间所有的月份

说明:

master.spt_values相当于一个数字辅助表,在sql中主要用到number这个字段

该表是从sybase继承过来的,是个内部字典表,供SQL Server内部使用。
我们可以在许多系统存储过程和函数的源代码中发现它的身影。其实可以将它理解成我们编程时常用的数据字典.

列名分别为名称、值、类型、下限、上限、状态;

类型列的取值含义:
D=Database Option P=Projection DBR=Database Role DC=Database Replication I=Index L=Locks V=Device Type
因为比较多,无法一一列举。其中类型P较为特殊,它只是0-2047(与版本有关)之间的数字的简单列表,作为对所有类型之间关系的预测。

参考:http://blog.csdn.net/whaxrl/article/details/50789894