Date Field data types varchar are incompatible with subtract operator in SSMS - sql

I've tried to search the answer for this but none of the solutions I've found have worked.
I need to subtract 2 date fields from one other: datearrival - date departed but these are both varchar and so the subtract operator won't work.
Can someone give me an answer in code, perhaps using cast and/or date diff to make this work?
my current code is:
DATEDIFF(dd,[ARRIVDAT],current_timestamp)-(dd,[DEPARTDAT],currenttimestamp) AS LengthOfStay
This is highlighting the column names as not being recognised, even though in the rest of the query the multi-bound identifiers are fine.
Any good answers please?

declare #ARRIVDAT varchar(12) ='1JAN18', #DEPARTDAT varchar(12) = '2FEB18'
select DATEDIFF(dd, #ARRIVDAT, #DEPARTDAT) LengthOfStay
I think it'll do an implicit conversion. You don't need cast or convert also.

You want the function DATEDIFF(). You can convert the values:
DATEDIFF(day, CONVERT(date, ARRIVDAT]), CONVERT(date, DEPARTDAT) AS LengthOfStay
If the implicit conversion doesn't work, then peruse the documentation for the appropriate format that does work.

Related

Get dates that are older than 30 dates from today

I have such a situation. I have a field namely [IBLREC] that is of NUMERIC type.
I usually just do it this way and it works
where cast(IBLREC as datetime) > DATEADD(DAY,-30,GETDATE())
However, for some reason it doesn't work for this table(?)
I basically get zero results.
Empty
When I comment out this line, I do see that the column has results for older than 30 days from today.
I don't understand what I am doing wrong, why it is not picking those dates up.
When comment out
Can someone advise me anything?
Thank you
You can find a more detailed answere here: Convert Date Stored as NUMERIC to DATETIME
(Including an explanation why you should not create a numeric-column for your dates)
Solution: To parse that numeric value you need to convert it as a text first, and then convert that text to a numeric value.
WHERE CONVERT(DATETIME, CONVERT(VARCHAR(8), IBLREC), 112) > DATEADD(DAY,-30,GETDATE())
AND IBLREC <> 0

How can I switch the Month and Day when the column format is M/D/Y?

I am not sure if this has already been answered but I could not find anything.
I am trying to convert the column of dates from MM/DD/YYYY to DD/MM/YYYY.
I must confess that I don't even know where to begin on this. I was thinking I might try an update statement but I am unsure as to how to format it. Any help would be appreciated.
You need to do two level of conversation :
select convert(varchar(12), convert(date, datecol, 101), 103)
In general, you need to fix the data-type (if that is in your hand) instead of doing conversation in SQL. Date formatting should be done at the presentation layer.
You can try this by fixing the data type in the actual table. For displaying purpose either on a webpage, reports or whatever.
SQL Server provides a number of options you can use to format a date/time string. In select, you can try one of the suggested methods as here.
For all these conversions you need to pass the date values in proper data type which may be the date or date-time.
Here is one of the examples of your illustration.
declare #DateInString varchar(20) = Cast(getdate() as Varchar(20))
select convert(varchar(12), convert(date, #DateInString, 101), 103)
You could also do Select Format(datecol, 'dd/MM/yyyy')
This will return your datetime field as a varchar - you should then be able to insert that into your target.

How to correct this delete query

I need to do a select query like this:
select *
from faults
where insertdate < DATEADD(DAY, -30, sessiondate)
The query should be correct but I get this error:
Conversion failed when converting date and/or time from character string.
Since, sessiondate contains a date but as string and not in date format.
Is there a way to do this query with a string instead of a date type?
The error seems pretty clear. insertdate and/or sessiondate are stored as strings. You should fix the data.
SQL Server has three ways to convert such values:
Implicitly by putting the strings in a place where date/times are expected.
Explicitly using CAST()/CONVERT().
Explicitly and flexibly using PARSE().
You need to figure out what your format is. They you can convert it. You've provided no information, but a typical method would be:
where insertdate < DATEADD(DAY, -30, TRY_CONVERT(date, sessiondate, <date style here>))
Usually the formats available with CONVERT() are sufficient (see here). Sometimes, you may need to use TRY_PARSE().
EDIT:
To support timestamps, then you need to convert to datetime2:
try_convert(datetime2, '2019-07-08T09:17:19+02:00')
You should be comparison to a value with a timestamp.

Converting from mmddyyyy to yyyymmdd with SQL

I should preface my question by saying I am very new to SQL (or any programming involving databases). I started learning SQL a couple of weeks ago when I decided to take on a data project.
I have been using SSMS in wrangling large tables in comma-separated text file format. I need to be able to sort by dates, and the current format is mmddyyyy, but when I try to sort by date it does not work.
I know that converting dates is something that gets asked a lot around here, but I haven't found any solutions that explain things for a newb like myself.
So far my guesses for a solution are to use the CONVERT or CAST solutions, but I'm not sure if that is the right approach. I have found several CAST/CONVERT posts but none have really applied to my situation.
I hate to have this as my first question, but I'd thought I'd take some down vote bullets if it means I could figure this out. Thank you.
Sample of what I'm trying to do:
SELECT *
FROM [databasename].[dbo].[table1]
WHERE [ column1] > 01012017;
I get the entire table back, unsorted.
Since your:
SELECT *
FROM [databasename].[dbo].[table1]
WHERE [ column1] > 01012017;
does not error, we could say that the [column1]'s datatype is either a character type (like VARCHAR, char), or datetime.
Since you are getting back all the data and I would think you don't have data in the future, it should be a varchar (or char) - with datetime that means 1900-01-01 + 1012017 days.
To make it a datetime you need to 'cast' your column1 which is in mmddyyyy form by first converting it to yyyymmdd style (which would work under any date and language setting):
cast(right([column1],4)+substring([column1],1,2)+substring([column1],3,2) as datetime)
and you would write that 01012017 as a string (quotes around) and also again in yyyymmdd format (it would be implicitly casted to datetime):
'20170101'
So your SQL becomes:
SELECT *
FROM [databasename].[dbo].[table1]
WHERE cast(right([column1],4) +
substring([column1],1,2) +
substring([column1],3,2) as datetime) > '20170101';
Having a date\datetime column as varchar and using like this would render the ability to use simple indexes but that is another matter. For now, this would return the data you want.
Assuming your column's datatype is [Date], try something similar to:
SELECT *
FROM [databasename].[dbo].[table1]
WHERE FORMAT([column1],'dd/MM/yyyy') >'01012017'
If it's string format, you'll have to use CONVERT() to convert the column to Date with a query like
SELECT *
FROM [databasename].[dbo].[table1]
WHERE CONVERT(NVARCHAR(10), [Column1], 112) >'01012017'
Refer to this W3Schools article if you need more help with the CONVERT clause

SQL Finding the date difference when two formats are different

I have a date stored in format like
18/1/2012 18:51:35
I have to find the difference in days between one date and current date. To get current date i am using getdate() which returns the below
2015-10-30 10:01:25.493
Currently i am using charindex and substring function to make to formats equal in datediff(). Is there a better way
I think this has been answered here:
Converting a date in MySQL from string field
where (i think) you basically would just, (haven't tested :/)
datediff(STR_TO_DATE(your_column_to_convert, '%d/%m/%Y %H:%M:%S'), CURRENT_DATE())
Assuming you using SQL Server, as the GETDATE() and CHARINDEX() are specific to MSSQL.
If the date 18/1/2012 18:51:35 is stored in VARCHAR, you could probably use
DECLARE #DateFromTable VARCHAR(20)
SET #DateFromTable = '18/1/2012 18:51:35'
SELECT DATEDIFF(DAY, CONVERT(DATETIME,#DateFromTable, 103), GETDATE());
Refer to Cast and Convert functions here.
Below is the MSSQL code which you are looking for.
DECLARE #column_date VARCHAR(50)
SET #column_date = '18/1/2012 18:51:35'
SELECT DATEDIFF(DAY,CAST(CONVERT(DATETIME,#column_date,103) AS DATETIME),GETDATE())
Try replacing your column with #column_date.
Hope it will help you.