一、前言
因为我公司要做财务结算前一天0:00:00至23:59:59的数据,利用到动态拼接SQL语句
我们需要明白声明DateTime 和 Date 获取的时间格式是不一样的,所以通过此计算有利于得到我们需要的时间段数据
二、测试数据展示(自己看print结果)
DECLARE @startDate DATE;DECLARE @startDateTime DATETIME;DECLARE @endDateTime DATETIME ;SET @startDate=GETDATE();SELECT @startDateTime=DATEADD(DAY,-1,@startDate); SET @endDateTime=DATEADD(second,-1,CONVERT(DATETIME,@startDate))print(@startDateTime)print(CONVERT(DATETIME,@startDate))print(@startDate)print(@endDateTime)
三、动态SQL语句
DECLARE @startDate DATE;DECLARE @startDateTime DATETIME;DECLARE @endDateTime DATETIME ;SET @startDate=GETDATE();SELECT @startDateTime=DATEADD(DAY,-1,@startDate); SET @endDateTime=DATEADD(second,-1,CONVERT(DATETIME,@startDate))declare @sql nvarchar(1000)set @sql='select * from E_OrdersLogistics where ForecastTime>='''+cast(ISNULL(@startDateTime,'') as nvarchar(100)) +''' and ForecastTime<'''+CAST(ISNULL(@endDateTime,'') as nvarchar(100))+''''print(@sql)exec(@sql)
如需转载,请注明出处,谢谢大家支持~
- 1楼lb1208
- 这样应该也可以吧,比如去8.17号的数据,,select * from table where timegt;#39;2015-08-17#39; and timelt;#39;2015-08-18#39;
- Re: 白猪
- @lb1208,恩。应该可以的,调试一下是否在日期范围取等号就好,我上面写得有点繁琐了,但是也可以学习一下,如果需求要求前一天某个时间段的数据,也可以灵活变通~另外按你的做法也要做一些赋值加减日期,只是逻辑会比较顺一点