Add Case Statement in Where Clause - sql

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))

Related

Use one of two dates in where clause

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

Removing Overlapping by adding a value to a date column caused an overflow

My question is related to this one . When I try to execute this query :
with toupdate as (
select t.*,
lag(enddate) over (partition by employee order by startdate) as prev_enddate
from MyTable t
)
update toupdate
set startdate = dateadd(day, 1, prev_enddate)
where startdate <> dateadd(day, 1, prev_enddate);
I am having this error message :
Adding a value to a 'date' column caused an overflow.
Knowing that :
SELECT MIN(BI_StartDate),MIN(BI_EndDate),MAX(BI_StartDate),MAX(BI_EndDate)
FROM MyTable
The ouput :
MinBIStart MinBIEnd MAXBIStart MAX BIEnd
1900-12-31 2017-06-27 2020-03-27 9999-12-31
I assume the problem is coming from the where clause:
update toupdate
set startdate = dateadd(day, 1, prev_enddate)
where (case when prev_enddate < '9999-12-31'
then 'false'
when startdate <> dateadd(day, 1, prev_enddate)
then 'true'
end) = 'true'
Or, you can replace the logic with:
where dateadd(day, -1, startdate) < prev_enddate

SQL Query with date range Male Female

I have a query that works but I need to incorporate in that query the following:
For male date is older or equals 3 months;
For female date is older or equals 4 months;
SELECT *
FROM Davaoci
WHERE DatumPoslednjegDavanja >= DATEADD(month, -3, GETDATE())
AND KrvnaGrupa = 'APos'
ORDER BY DatumPoslednjegDavanja DESC
Use a CASE statement:
SELECT * FROM Davaoci
WHERE DatumPoslednjegDavanja >= DATEADD(
month,
CASE WHEN Pol = 'M' THEN -3 ELSE -4 END,
GETDATE()
)
AND KrvnaGrupa = 'APos'
ORDER BY DatumPoslednjegDavanja DESC
EDITED: Based off your comments on the question, I made some adjustments to my answer. Working through our language barrier, I think this is what you're looking for.
NOTE: The way I have this set up now, it will only accept rows where the Pol column has an 'M' or 'F'. You may need to adjust the ELSE as needed.
SELECT *
FROM Davaoci
WHERE
KrvnaGrupa = 'APos'
AND CASE
WHEN Pol = 'M'
THEN DatumPoslednjegDavanja >= DATEADD(month, -3, GETDATE())
WHEN Pol = 'F'
THEN DatumPoslednjegDavanja <= DATEADD(month, -4, GETDATE())
ELSE FALSE
END
ORDER BY
DatumPoslednjegDavanja DESC;

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)