Sorry for the noob SQL question. I have a table in SQL with a DateTime column. I need to run a script daily to show any lines from 8am yesterday until 8am today. So for example, today I would run:
select * from Table Where DateTime > '2020-12-30 08:00:00.000' and DateTime < '2020-12-31 08:00:00.000'
I also know that I could run this, but this will only give me the previous day through the current time:
select * from Table Where DateTime >= DATEADD(day,-1, GETDATE()) and DateTime < GETDATE())
But is there a trick to creating the script so I can get 8am yesterday through 8am today without manually editing the script every day?
Advertisement
Answer
I would recommend:
select * from mytable where datetime >= dateadd(hour, 8, dateadd(day, -1, convert(datetime, convert(date, getdate())))) and datetime < dateadd(hour, 8, convert(datetime, convert(date, getdate()))))