Delete records based on dates - sql-server

I have a database "DB" and I want to delete records from table "MyRecords" which are of future ("RecordDates" which are more than today just to avoid date change on system) and less than x no. of days from today.
That "x" may vary. Moreover, I want to execute same type of command with month and year also.
I am using SQL Server and C#.

To delete records which are in the future and less than n days in the future you could use T-SQL such as this:
DELETE FROM DB.table WHERE
(date > GETDATE() AND date < DATEADD(day, 5, GETDATE()));
In this case n is 5.
You can see all the arguments to DATEADD() at DATEADD (Transact-SQL)

This query will delete all records that are later than today's date, but less than 30 days in the future. You could replace "30" with a variable so you could determine how many days in the future to delete.
DELETE FROM Table
WHERE
TABDate > GETDATE() and TABDate < DATEADD(day, 30, GETDATE())
UPDATE
To delete all records less than 30 days in the past, you would change the query to look like this:
DELETE FROM Table
WHERE
TABDate > DATEADD(day, -30, GETDATE()) AND TABDate < GETDATE()
Also note that all these examples are calling GETDATE() which also has a time component as well as a date, so care must be taken in that anytime you see a statement like < GETDATE() you are not just deleting records with a date before, say, 2011-09-29, you are deleting all records with a date before '2011-09-29 17:30'. So be aware of that if you table dates contain times as well.

You can use the query DELETE FROM DB.table WHERE date > now() or WHERE date > unix_timestamp(), depending on how you are storing your dates. (i.e. date-time vs. timestamp).

Related

SQL query for removing current and future dates?

I would like to filter out all records that have a date in the future AS WELL AS any records in the current month. I attempted to use this query:
...
WHERE (Month(DueDate) < Month(getdate()) AND (Year(DueDate) <= Year(getdate())))
The issue is that it doesn't return any results that were previous year but a month that is greater than the current. ie: Today's date is 9/12/18, it would not return any records that had a month of 10, 11 or 12 regardless of the year.
This will filter off any records with a DueDate after the first of the current month.
WHERE DueDate < DATEADD(MONTH ,DATEDIFF(MONTH, 0, GETDATE()), 0)
EDIT: I had >. Should've been <.
Try something like:
SELECT ...
FROM ...
WHERE DueDate < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1);
This solution uses DATEFROMPARTS function for which you can see more information in the documentation. The idea is to get the first of the current month for the current year and select only those rows whose DueDate is before the given date and time.
Also, instead of GETDATE() (link) function you might want to check out GETUTCDATE() (link) if it's more suited to your needs.

dynamically changing dates in a temp table

So i have a very specific task. I run some sql statements within which there is a temp table which contains date ranges specific to countries.
e.g.
INSERT INTO #dateRange(durationDesc, contryCode,startDate,endDate)
VALUES ('Weekly - TY','UK','20160919','20160925')
,('Weekly - LY','UK','20150921','20150927')
,('Weekly - LW','UK','20150912','20150918')
So, corresponding week previous year. The other range is month to date.
Whats the best way to do this? I'd prefer one where i only need to enter one date and the rest can be updated.
Any questions, feel free to ask.
You can always get current system datetime by GETDATE(), and then modify it accordingly by DATEADD()
For example:
SELECT DATEADD(YEAR, -1, GETDATE()) -- Result in 1 year prior the current system datetime.
SELECT DATEADD(MONTH, 13, GETDATE()) -- Result in 13 months after the current system datetime.
In your code snippet you seems to be converting the datetime into yyyymmdd string format (Although I highly doubt the necessity), which can be achieve by a CONVERT:
SELECT CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
For example if today is 10/26/2016, then it should show result as 1 year prior to today in yyyymmdd format, 20151026

Date filter on column in sql

I have query that filtered by date, for now it take only the last 24h from the moment I execute it, for doing that I'm using the next code:
( DateDiff(HH, vw_public_task.complete_date, getdate()) < 25)
There is a way that my date filter will give query results for the last 24h but not depending on my current hour but according to "day 08:00am" -- "day+1 08:00am" at any time that I execute it?.
For example if I execute my query now I want to see date results from yesterday 08:00am till today 08:00am.
You can calculate yesterday 8am using the formula:
-- Yesterday at 8 am.
SELECT
DATEADD(HOUR, 8, CAST(CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS DATETIME)) AS Yesterday8AM
;
GetDate returns the current date. The innermost date add subtracts one day. Casting this as a date removes the timestamp. Casting this back to a DateTime gives yesterday at midnight. Now we are dealing with a DateTime we can use date add, again, to add 8 hours.
If you are using SQL Server 2012, or above, consider the native function DATETIME2FROMPARTS instead.
Use Date() (How to part DATE and TIME from DATETIME in MySQL).
( DateDiff(HH, vw_public_task.complete_date, Date(getdate())+8 ) < 25)

Only filter my time in SQL Server where clause

I am new to SQL and Programming in general. I have a datetime field which I want to use to filter my results but only on the time portion.
For example I need to run a report from 2pm yesterday to 7am current day. I cannot hard code the dates because this report needs to run daily. This Query will run from a stored procedure automatically.
I have tried AND clm.createDtTm > DATEADD(d, -1, GETDATE()), which goes back one day but not the time range I need.
I tried this: AND (datepart(hh, '11:02:54.107') = 7)<--To be honest not even sure what I am doing here.
I am not sure if this is even possible, but if I can get results for one day back I am assuming there has to be a way to narrow that day between hours.
Any help would be appreciated.
Thanks,
Abdul
This should do the trick, it filters out rows that do not fall in the date interval, from 7pm yesterday to 7am today.
WHERE
createDtTm >= DATEADD(HOUR, 14,CAST(DATEADD(DAY,-1, CAST(GETDATE() AS DATE)) AS DATETIME))
AND createDtTm <= DATEADD(HOUR, 7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))
I suggest something like this:
SELECT(DATEADD(d,-1,GETDATE()))
FROM table
WHERE (DATEADD(d,-1,GETDATE())) = rowloadtimestamp
HAVING DATEPART(HH,rowloadtimestamp) BETWEEN 13 AND 24
UNION
SELECT GETDATE()
FROM table
WHERE GETDATE() = rowloadtimestamp
HAVING DATEPART(HH,GETDATE()) BETWEEN 1 AND 7
Assuming you have a rowloadtimestamp field this should work for you.
What do you mean with „I can not hardcode the dates” ? Do you mean the time interval is variable, or is it fixed, or are you referring to the exact dates? I'm not sure I understand.
In case of MySQL you can do something like:
SELECT data, date FROM table WHERE date < DATE_SUB(NOW(), INTERVAL 2 DAY);
This Query will get you the last two days. You can vary the interval by replacing the „2” with a variable if that is possible in your case.

Filtering columns based on a date in a field for current week, past weeks, and future weeks

Example Table:
(Column Heading) Total Interviews of everyone --- (Row Heading) Interview Requested
(Column Heading) Number of interviews this week -- (Row Value) Count all the dates scheduled this week that have the status: "Interview Requested" e.g 4
(Column Heading) Number of interviews next week -- (Row Value) Count all the dates scheduled next week that have the status: "Interview Requested" e.g 6
First of all i'll like to aploigise about my makeshift table, it seems that i cant use pictures since im a new member.
I am also new to using reportbuilder and sql and have been trying to figure out how i can count the amount of dates that fall between certain date ranges in a report.
Like ive stated in the makeshift field called "Number of interviews this week" I wish to count all the dates scheduled for the current week, the week after, the week before and so on based on a date field. I then plan to break this table down to show all the interviews a single person has schedueled.
The issue I am having is that there will be many dates spanning different months/days. So Im not sure how i can represent this with DateDiff or other date features, because the table is meant to be a live representation of the current interviews.
Is what i'm trying to do even possible using report builder?? If so any tips would be great, if not then thanks for taking the time to look at my question.
As Requested Dataset Fields:
[UserName] (User table), [InterviewStatus] (Interview table), [DateUpdated] (Interview Table)
Those are the main ones that will be used in the report
If you just want to count the number of columns of each field, you can use the sql statement COUNT() see COUNT().
You can do the common query like this:
SELECT COUNT(fieldName1), COUNT(fieldName2), ... , COUNT(fieldNamen) FROM <tableName>
Also try to show your codes so that your question will be more clarified.
You can use the generic select statement from your interview table filtering in the where clause for dates between the beginning of the current week and the end of the next.
Then the two fields would be a sum of 1 if the date falls within the current week or next.
EDIT:
Example below will give the number of dates within this week. Taken from another question:
Select InterviewStatus,
Sum(Case when DateUpdated >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
AND DateUpdated < CAST(CONVERT(VARCHAR(10), DATEADD(dd, (8 - DATEPART(dw, GETDATE())), GETDATE()), 120) AS DATETIME)
Then 1
Else 0 end)
as NumberInCurrentWeek
From InterviewTable
Where DateUpdated >= DATEADD(dd, -(DATEPART(dw, GETDATE()) -1), GETDATE())
AND DateUpdated < CAST(CONVERT(VARCHAR(10), DATEADD(dd, (8 - DATEPART(dw, GETDATE())), GETDATE()), 120) AS DATETIME)
Group by InterviewStatus
This just needs to be tweaked to your exact circumstance. For example alter the 8 by 7 will capture the current fortnight.
Then produce a simple table based on the query.

Resources