SQL获取前一天0:00:00至23:59:59数据

时间:2023-03-09 07:48:07
SQL获取前一天0:00:00至23:59:59数据

一、前言

因为我公司要做财务结算前一天0:00:00至23:59:59的数据,利用到动态拼接SQL语句

我们需要明白声明DateTime 和 Date 获取的时间格式是不一样的,所以通过此计算有利于得到我们需要的时间段数据

二、测试数据展示(自己看print结果)

DECLARE @startDate DATE;
DECLARE @startDateTime DATETIME;
DECLARE @endDateTime DATETIME ;
SET @startDate=GETDATE();
,@startDate);
,CONVERT(DATETIME,@startDate))

print(@startDateTime)
print(CONVERT(DATETIME,@startDate))
print(@startDate)
print(@endDateTime)

SQL获取前一天0:00:00至23:59:59数据

三、动态SQL语句

DECLARE @startDate DATE;
DECLARE @startDateTime DATETIME;
DECLARE @endDateTime DATETIME ;
SET @startDate=GETDATE();
,@startDate);
,CONVERT(DATETIME,@startDate))

)
))  ))+''''

print(@sql)

exec(@sql)

SQL获取前一天0:00:00至23:59:59数据