Updating table column date with case expression? - sql

I need to update column8 with data depending on two other columns with dates (date1 and date2) - if date1 is later than date2 then column8 is YES otherwise its NO.
I wrote this:
update table1
set delay = case when date1 > date2 then 'YES'
when date2 is NULL then 'YES'
else 'NO'
end
The problem is that it is probably not comparing the dates but length of the expression, because I have no in every column except for null columns... It tells me that it probably does not know I want it compare as a date But the columns in database are in date format YYYY-MM-DD.
Is there any way to update my code or in adding something to make compare the dates and not the string lengths?
Thanks!

You can try CAST function:
WHEN CAST(date1 AS DATE) > CAST(date2 AS DATE)

Related

Difference Between two dates or N/A

I have a calculation between two dates.
What I'm trying to do is if the start date is before 03/07/20 then show N/A otherwise the difference between the two dates
case
when StartDate < cast('03-07-20' as date) then
'N/A'
else
DATEDIFF(day, cast(StartDate as date), cast(SwabDate as date) )
end
as Days_From_First
I get
Conversion failed when converting the varchar value 'N/A' to data type int.
Warning: Null value is eliminated by an aggregate or other SET operation.
Thank you for your help
All branches of a case expression must return the same datatype, so you can't have a branch return a string ('NA') and the other a integer (as returned by datediff()). What happens when you do that is that SQL Server prioritizes the numeric datatype, and hence attempts to coerce 'NA' to an integer - which fails.
You could cast the return value of datediff() to a string - but I would not recommend that. Probably, using null is the best way to go here: in SQL, that's usually how we represent the absence of data:
case when StartDate >= '20200703'
then datediff(day, cast(startdate as date), cast(swabdate as date))
end as Days_From_First
Note that I changed the date comparison to use literal '20200703', that SQL Server is able to unambiguously understand as a date in format YYYYMMDD.
You need to cast the results to be strings:
(case when StartDate < cast('2020-03-07' as date)
then 'N/A'
else convert(varchar(255), datediff(day, cast(StartDate as date), cast(SwabDate as date) ))
end) as Days_From_First
That said, I would really suggest that you forget about 'N/A' and just use NULL.
Also, I don't know if your date is 2020-03-07 or 2020-07-03. That is why you should use standard date formats.

How to compare one field to another using LIKE

I want to so something like the following:
SELECT * FROM TABLE1
WHERE DATE1 LIKE DATE2 + '%'
However, when I try this I get the following error:
"5407: Invalid operation for DateTime or Interval"
I am working in Terdata SQL Assistant
You can't use like to compare dates, like is to compare string (varchar), then you can cast this dates to varchar or better way is cast both dates to the same format, for example:
SELECT * FROM TABLE1
WHERE convert(varchar, DATE1, 103) = convert(varchar, DATE2, 103)
This way cast dates to format: DD/MM/YYYY
If you wanna cast to another formats I let you a link that explain more types: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
You could potentially just format the dates the same way to compare them.
WHERE FORMAT(DATE1, 'dd/mm/yyyy') = FORMAT(DATE2, 'dd/mm/yyyy')
date2 is less than 1 day later
where datediff(d,date1,date2) < 1
Since your using like ... you could mean within a day before or after.
abs(datediff(d,date1,date2)) < 1

If I have a query that compares two dates in SQL Server, what will happen if one of the dates is null?

If I have a query that has a WHERE clause like:
where date1 > date2
What will happen if date2 is null? Do I need to specify that date1 and date2 both be not null?
The types are DATE()
It will try to compare date1 to NULL and it will evaluate to unknown.
WHERE '2013-07-18' > NULL
is unknown. See my blog post on NULL behavior in 3 valued logic.
You will want to use a function like ISNULL around date2 or explicitly write out the logic. Using ISNULL will prevent an index from being used, however. You could write:
WHERE (date1 > date2 OR date2 IS NULL)
Either use an ISNULL on the nullable date and replace it with a default date or other field.
For instance:
Where Date1 > ISNULL(date2, '1900-01-01').
Better yet, replace the hardcode with a default parameter.
Declare #defaultvardt DATE = '1900-01-01'
Where Date1 > ISNULL(date2, #defaultvardt)
always UNKNOWN. NULL value must be treated with IS NULL statement
Try this example:
declare #d1 datetime
declare #d2 datetime
set #d1 = GETDATE()
select
case
when #d1 > #d2 then 'OK'
else 'KO'
end
Any value, when compared for equality to NULL, will yield a value of False, even when comparing NULL to NULL.
You can use the IS NULL operator to check values for NULL.

sql query condition on temporary column

I pondered on this one a little bit. Found a few question on SO but none of them addressed my problem.
What I am trying to do is compare two dates in a table, I am returning the greater of the two using a case statement
select <-- similar code but not actual code
...
case
when date1 > date2 then date1 else date2 end as lastDate
Everything fine upto this point. I get the greater date in my result. The problem is I want to apply a WHERE clause on LastDate. Since the lastDate is a temporary column, it won't be accept in WHERE clause I came up with this syntax
if #cur_date != null <---- this is parameter to my store procedure, if not null then
case when date1 > date then date1 like '2011-%' else date2 like '2011-%'
But I get an error for the misplaced 'like' keyword. I think a statement can not be returned after the 'then' keyword in case statement. How do I do this? Do I have to use temporary table for this? I want to find the best approach.
Use your same syntax in the WHERE clause:
WHERE case when date1 > date2 then date1
else date2 END
like '2011-%'
EDIT:
Sample code for Date comparison:
WHERE case when date1 > date2 then CAST(date1 as varchar)
else CAST(date2 as varchar) END
like '2011-%'

Compare Date portion of Datetime in SQL

I am working with SQL and I have two columns with datetime field.
What I want to do is just compare the date portion of the these datetime fields and see if there are different.
For example,
col1 | col2
'2010-01-02 23:58:00.000' | '2010-01-03 06:21:00.000'
'2010-01-04 16:03:00.000' | '2010-01-04 21:34:00.000'
Row1's dates are different but row2 are same
I am thinking something like datediff(day,col2,col1) < 1 //Then this is different else they are same.
Not sure how to parse the date then compare two fields.
abs(datediff(day, col1, col2)) > 0
This should work in many databases:
DATE(col1) = DATE(col2)
By "using SQL" I assume you meant SQL Server.
For all records where col1 and col2 are different days, you can use !=
SELECT *
FROM TBL
WHERE DateDiff(d, col1, col2) != 0
Check out the DatePart function. It enables extracting day, month, year, etc. from a date, which appears is what you are asking about.
http://msdn.microsoft.com/en-us/library/ms174420.aspx
If you are using SQL Server (version 2008 and above), you can compare just the date portions of the datetime fields by casting them to the DATE format:
CAST(MyDate AS DATE) >= CAST(TheOtherDate AS DATE)