Relative Date Range in T-SQL

I am trying to select for all elements where createDt is in the last two weeks. I tried this code but it does not work.

SELECT * FROM dbo.mytable WHERE CreateDt > dateadd(d,-15,CreateDt) 

Can someone tell me the correct way to do this?

+4
source share
4 answers
 WHERE CreateDt > dateadd(d,-15,CreateDt) 

it should be

 WHERE CreateDt > dateadd(d,-15,getdate()) 

Presumably.

All NOT NULL CreateDt values โ€‹โ€‹will match your current condition when you compare a column with your value minus 15 days - not 15 days before the current date and time.

+9
source

"Where created> (created - 2 weeks)"? I do not think so;)

Try the following:

 ... where createdate > dateadd (d, -15, getdate()) 
+2
source

You check if CreateDt is more than 15 days before itself. I guess you get a lot more records than you expect.

I would do something like this (for readability)

 Declare @CheckDate DateTime Set @CheckDate = dateadd(d, -15, GetDate()) SELECT [Columns] from dbo.mytable WHERE CreateDt > @CheckDate 

Also remember to call your columns - do not use "SELECT *" under normal conditions.

+2
source

I believe that this is what you want.

 SELECT * FROM dbo.mytable WHERE CreateDt > dateadd(wk,-2,getdate()) AND CreateDt < getdate() -- possible bad data 
+2
source

Source: https://habr.com/ru/post/1390272/


All Articles