Use one of two dates in where clause - sql

I need to delete all records in a table where the CreatedDate or ModifiedDate is greater than x. The logic is as follows:
If ModifiedDate is not null then use this value
Otherwise use the CreatedDate value
Not applying the if/else statement correctly.
delete * from table where
-- how to implement the following
if ModifiedDate is not null then ModifiedDate < GETDATE() - 30
else CreatedDate < GETDATE() - 30

Use this where clause:
where coalesce(ModifiedDate, CreateDate) < dateadd(day, -30, getdate())

Use case statment
Delete * From tableX
CASE WEHN ModifiedDate is not null and < Getdate() - 30 THEN -- your logic
Else -- CreateDate < Getdate() - 30 END

Related

SQL Server 2008 - update a field if date is older than 60 days

I have three fields in my user_Group table: Banner_flag, warning_Date1 & warning_Date2
What i want to do is update warning_Date2 to today's date & also set banner_flag to = '2' if the date in warning_Date1 is over 60 days old and do nothing to those that don't meet this criteria.
I'm pretty sure I need a case statment but am having trouble writing it effectively. Any help appreciated, thanks.
In one single update statement can do, use DATEDIFF
UPDATE user_Group SET Banner_flag = 2, warning_Date2 = GETDATE()
WHERE DATEDIFF(DAY, warning_Date1, GETDATE()) >= 60
AND Banner_flag < 2 --This subject to your mechanism
You could set up a job to update the table. Run it once per day or per hour or per minute, or whatever.
However, I think it is easier to use a view or computed column. Start by renaming your existing warning_date2 and banner_flag columns to something like _warning_date2 and _banner_flag and then:
alter table t add warning_date2 as
(case when dateadd(day, 60, warning_date1) <= cast(getdate() as date)
then cast(getdate() as date) else _warning_date2
end);
alter table t add banner_flag as
(case when dateadd(day, 60, warning_date1) <= cast(getdate() as date)
then '2' else _banner_flag
end);
Check the below query,
UPDATE user_Group
SET Banner_flag = '2', warning_Date2 = GETDATE()
WHERE warning_Date1 > DATEADD(d, -60, GETDATE())

Add Case Statement in Where Clause

I need to add a case statement in a where clause. I want it to run either statement below depending on the value of TermDate.
Select *
from myTable
where id = 12345
AND TermDate CASE
WHEN NULL THEN
AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)
ELSE
AND GETDATE < TermDate
END
Why not just use an OR condition?
SELECT *
FROM myTable
WHEN id = 12345
AND ((TermDate IS NULL AND
getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)) OR
GETDATE() < TermDate)
Since we all posted three exact answers, obviously too much, here a version that uses your case when construction.
use this:
select *
from myTable
where id = 12345
AND case
when TermDate IS NULL
AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)
then 1
when GETDATE < TermDate
then 1
else 0
end
= 1
You can accomplish this using ANDs and ORs. Try the following query.
Select *
From myTable
where id = 12345
AND ((TermDate IS NULL
AND GETDATE() BETWEEN StartDate AND DATEADD(dd, 30, StartDate))
OR (GETDATE() < TermDate))

How to display result in two column form one column resource with different where

I try to count record which is on current date and pass date from date column
DATE
'2013-03-04 00:00:00'
'2013-02-04 00:00:00'
'2013-02-04 00:00:00'
if today is '2013-03-04 00:00:00'
the result should be
CURRENT_DATE = 1
PASS_DATE = 2
I Don't know how to query it form one resource but different where condition
1st - date >= '2013-03-04 00:00:00'
2nd - date < '2013-03-04 00:00:00'
PLEASE HELP
I suggest using two sub-queries within a SELECT clause
select
(select count(*) from MyDates where DateValue < getdate()) as PastDate,
(select count(*) from MyDates where DateValue >= getdate()) as CurrentDate
You can replace getDate() with a date parameter or a hard-coded value such as '2013-03-04' if you wish.
One way to do it is to query for all dates and place 1\0 according to your condition
then just query again from the table an sum the columns.
SELECT sum([CURRENT_DATE]), sum([PASS_DATE])
FROM
(
SELECT
ID,
case when myDate >= getDate() then 1 else 0 end as [CURRENT_DATE],
case when myDate < getDate() then 1 else 0 end as [PASS_DATE]
FROM mytable
) as SourcTbl
Here is a SQL Fiddle http://sqlfiddle.com/#!3/e9c19/8

Check if DateTime in DB is more than 90 days old via Stored Procedure

UPDATE
Evidently I didn't include enough data, sorry!
What I need to do is set 'campaign_Status' = 6 when 'campaign_Date' is more than 90 days old.
Hi,
I have a column (campaign_Date) which stores a DATETIME. Using a Stored Procedure I need to check if the stored date is 90 days old (or more).
Any help would be great.
Thanks.
This will return all old campaigns:
SELECT *
FROM mytable
WHERE campaign_Date <= DATEADD(day, -90, GETDATE())
This will select 1 if campaign is old, 0 otherwise:
SELECT CASE WHEN campaign_Date <= DATEADD(day, -90, GETDATE()) THEN 1 ELSE 0 END
FROM mytable
Note that the first query condition is sargable: it will allow using an index to filter the dates.
This will update all old campaigns with status 6:
UPDATE mytable
SET campaign_status = 6
WHERE campaign_Date <= DATEADD(day, -90, GETDATE())
See the DateAdd function
http://msdn.microsoft.com/en-us/library/ms186819.aspx
SELECT *
FROM MyTable
WHERE Campaign_Date <= DateAdd (d, -90, GetDate())
Here's a variation on the previous answers, wrapped in a stored procedure (as seemed to be asked):
CREATE PROC sp_Campaign_Archive AS
UPDATE [Campaign Table]
SET Campaign_Status = 6
WHERE DateDiff(day,Campaign_Date,GetDate()) >= 90
GO
SELECT IIF(DATEDIFF(d, campaign_date, getdate()) >= 90, true, false)
AS IsNinetyOrMoreDaysOld
FROM myTable
EDIT: If you wish to pick records which are 90 or more days old,
SELECT campaign_date
FROM myTable
WHERE DATEDIFF(d, campaign_date, getdate()) >= 90
select campaign_Date,
case when getdate() - campaign_Date >= 90 then 'yes' else 'no' end as Is90DaysOldOrMore
from MyTable
UPDATE:
You can update the records like this:
update MyTable
set campaign_Status = 6
where getdate() - campaign_Date >= 90
Because this status will go out of date rapidly because it is date-dependent, you could make it a calculated column instead.

SQL statement to select all rows from previous day

I am looking for a good SQL Statement to select all rows from the previous day from one table. The table holds one datetime column. I am using SQL Server 2005.
get today no time:
SELECT dateadd(day,datediff(day,0,GETDATE()),0)
get yestersday no time:
SELECT dateadd(day,datediff(day,1,GETDATE()),0)
query for all of rows from only yesterday:
select
*
from yourTable
WHERE YourDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND YourDate < dateadd(day,datediff(day,0,GETDATE()),0)
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
It's seems the obvious answer was missing. To get all data from a table (Ttable) where the column (DatetimeColumn) is a datetime with a timestamp the following query can be used:
SELECT * FROM Ttable
WHERE DATEDIFF(day,Ttable.DatetimeColumn ,GETDATE()) = 1 -- yesterday
This can easily be changed to today, last month, last year, etc.
SELECT * from table_name where date_field = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
Its a really old thread, but here is my take on it.
Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.
SELECT * FROM TABLE_NAME WHERE
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0
In the above case X will be -1 for yesterday's records
This should do it:
WHERE `date` = CURDATE() - INTERVAL 1 DAY
Can't test it right now, but:
select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)
In SQL Server do like this:
where cast(columnName as date) = cast(getdate() -1 as date)
You should cast both sides of the expression to date to avoid issues with time formatting.
If you need to control interval in more detail, then you should try something like:
declare #start datetime = cast(getdate() - 1 as date)
declare #end datetime = cast(getdate() - 1 as date)
set #end = dateadd(second, 86399, #end)
Another way to tell it "Yesterday"...
Select * from TABLE
where Day(DateField) = (Day(GetDate())-1)
and Month(DateField) = (Month(GetDate()))
and Year(DateField) = (Year(getdate()))
This conceivably won't work well on January 1, as well as the first day of every month. But on the fly it's effective.
Well, its easier to cast the datetime column to date and than compare.
SELECT * FROM TABLE_NAME WHERE cast(COLUMN_NAME as date) =
dateadd(day,0, convert(date, getdate(), 105))
A simple alternative
Select GETDATE() - 1
Change 1 to go back that many number of days
PS : This gives you timestamp accuracy.
This worked a charm:
SELECT * FROM mytable WHERE date(mydate) = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
subdate(now(),1) will return yesterdays timestamp
The below code will select all rows with yesterday's timestamp
Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)