SQL显示某月全部日期明细<存储过程>
方法一:
1 declare @date datetime 2 declare @end datetime 3 set @date = DATEADD(d,-day(getdate())+1,getdate()) 4 set @end =DATEADD(month,1,@date) 5 create table temp 6 ( 7 [Date] datetime 8 ) 9 while(@date < @end) 10 begin 11 insert into temp values(@date) 12 set @date=DATEADD(d,1,@date) 13 end 14 select * from temp 15 drop table temp
方法二:
1 declare @s varchar(6) 2 set @s='201702' 3 4 declare @date smalldatetime 5 set @date=@s+'01' 6 7 declare @i smallint 8 set @i=0 9 while @i<DATEDIFF(day, @date, dateadd(month, 1, @date)) 10 begin 11 print convert(varchar(10), dateadd(day, @i, @date), 120) 12 set @i=@i+1 13 end
执行结果:
下面是我整理的一些SQL日期格式:
1、获取系统日期: GETDATE()
2、select convert(varchar(10),getdate(),120) --获取当天的日期
3、select MONTH(CDate) as monh,YEAR(CDate) as yearh from Table_XJRecord where DATEPART(m,[CDate])=5 --设置某列列名为monh,yearh
4、select * from Table_XJRecord where datediff(month,[CDate],getdate())=0 //查询当月数据
5、select * from Table_XJRecord where datediff(month,CDate,getdate())=0 and Status in (2,3)--查询当月的数据并且满足列名status 为2 or 3的情况--
6、select DateDiff("D",getdate(),'2017-04-01')--查询现在距离某个时间的时间
select * from Table_XJRecord where datediff(month,[CDate],getdate())=0 -- =0 查询当月数据 =1 查询上个月数据--=2查询上上个月 以此类推
7、格式化日期: CONVERT(VARCHAR,GETDATE(),20) --20表示20位,日期格式为yyyy-mm-dd hh:mm:ss 10表示的日期格式为yy-mm-dd 120表示的日期格式为yyyy-mm-dd