小弟要实现一个功能,就是查询 当时间小于当前时间 或者 时间在今天到往后的10天 并且 用户名是john的信息,可是我这样写碰到了个问题,数据库只查询了小于当前时间并且用户名是john的信息,忽略了今天往后10天的信息,我试着在 (usertime<getdate() or usertime between getdate() and getdate()+10)加个括号,结果什么信息都没了,求解应该如何写呢?
select * from table where usertime<getdate() or usertime between getdate() and getdate()+10 and username='john'
select * from table where usertime<getdate() or usertime between getdate() and getdate()+10 and username='john'
日期不能这么加,使用函数DATEadd函数
参数
datepart指定要返回新值的日期的组成部分。下表列出了 Microsoft SQL Server 2005 可识别的日期部分及其缩写。日期部分 缩写
year
yy, yyyy
quarter
qq, q
month
mm, m
dayofyear
dy, y
day
dd, d
week
wk, ww
weekday
dw, w
hour
hh
minute
mi, n
second
ss, s
millisecond
ms
number用于与 datepart 相加的值。如果指定了非整数值,则将舍弃该值的小数部分。例如,如果为 datepart 指定 day,为 number 指定 1.75,则 date 将增加 1。date表达式,用于返回 datetime 或 smalldatetime 值,或日期格式的字符串。有关指定日期的详细信息,请参阅 日期和时间 (Transact-SQL)。如果只指定年份的后两位数字,则小于或等于 two digit year cutoff 配置选项值的后两位数字的值将与截止年份处于同一世纪中。比此选项值的后两位数字大的值先于截止年份的世纪。例如,如果 two-digit year cutoff 为 2049(默认值),则 49 被解释为 2049,而 2050 被解释为 1950。为避免歧义,请使用四位的年份。 返回类型
返回 datetime。但是,如果 date 参数为 smalldatetime,则返回 smalldatetime。
以下示例将输出 AdventureWorks 数据库中订单的时间范围的列表。此时间范围为当前订单日期加上 21 天。 复制代码
USE AdventureWorks;
GO
SELECT DATEADD(day, 21, OrderDate)AS TimeFrame
FROM Sales.SalesOrderHeader;
GO
where usertime < getdate() + 10 and username='john' 用这个条件试试。如果没有记录出来或者只有今天前的记录出来,那么说明你原来的代码没有问题,只是没有今天往后10天的数据。
要加上括号
select * from table where usertime<getdate() or (usertime between getdate() and getdate()+10 and username='john')
select * from table where usertime<getdate()
union all
select * from table where usertime between getdate() and getdate()+10 and username='john'
select * from tb where usertime<dateadd(dd,10,getdate()) and username='john'
select * from table where usertime<getdate() and username='john'
union
select * from table where usertime between getdate() and getdate()+10 and username='john'
inner join tb_terminal t on s.t_id=t.t_id inner join tb_vip v on t.vip_id=v.vip_id where
t.endtime <getdate() or t.endtime between getdate() and getdate()+15 and v.LoginName='john'