Get dates that are older than 30 dates from today - sql

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

Related

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.

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

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

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.

Can't convert YYYYMMDD to date

I'm trying to view software that has been installed within the last 30 days. The format of my date is 20150327. When I try to the following condition in the where clause
and DateDiff(day,arp.InstallDate0,GetDate()) < 30
I receive the following error message:
Conversion failed when converting date and/or time from character
string.
I have also tried the following and was unsuccessful:
CONVERT(varchar(8),arp.InstallDate0,112)
As well as:
ISDATE(CONVERT(datetime,arp.InstallDate0,112))
When I add ISDATE, it finally runs the query, but it is not showing any data and I know that there are installs within the last 30 days, so I'm thinking the date is still not being recognized.
EDIT The InstallDate0 column is nvarchar.
You do not need a conversion format for YYYYMMDD when converting to date, datetime2, and datetimeoffset. SQL Server recognizes this ISO standard format with no conversion in these cases, regardless of internationalization settings (there is one setting that affects my preferred format of YYYY-MM-DD; the documentation is here). So, you could do:
where cast(arp.InstallDate0 as date) > dateadd(day, -30, getdate())
At this point: "Shame on you for storing dates as strings."
That said, it is better (in your case) to do the comparison as strings rather than dates. You have a good date format for this, so:
where arp.InstallDate0 > convert(varchar(8), dateadd(day, -30, getdate()), 112)
Why is this better? With no functions on the column name, the query can take advantage of an appropriate index (if one is available).
You must use the syntax below, as the first argument for the CONVERT function is the target data type
CONVERT(datetime,'20150327',112)
You must use the syntax below:
WHERE
DATEDIFF(day, CONVERT(datetime, arp.InstallDate0, 112), GetDate()) < 30
Try converting the format using a converter to convert it to a date/or time string through conversion of its characters, then using the string to convert the numbers into a more usuable format with additional conversion
CONVERT(datetime,'20150327',112)

SQL: Counting dates formatted as varchar

The task:
I need to count every record in a table that was added after 07/01/2011.
Info:
There is a column in the table "Date_added" which is formatted as varchar and contains dates in format mm/dd/yyyy.
What I've tried:
I tried the following query:
SELECT count(date_added) FROM Abatements_Doc WHERE date_added >= '07/01/2011'
Unfortunately it counted any date where the month was greater than 07 regardless of the year or day. I'm at a loss as to how I should format my query to get it to read the dates properly instead of by ascii sort. In my research I discovered the CAST and CONVERT options, but am not sure how to use them, or which one I should use if any. I'm extremely new to SQL, and want to make sure I don't mess up the data in the table. I just need to get the count as specified above without altering the data in the table in any way. Any help in this regard will be very much appreciated. Thanks in advance.
I didn't test. But try convert statement.
SELECT count(date_added)
FROM Abatements_Doc
WHERE convert(datetime,date_added,1) >= convert(datetime,'07/01/2011',1)
(1) don't use mm/dd/yyyy as your date format. Use a safe and unambiguous format; the only one I trust for DATETIME/SMALLDATETIME is YYYYMMDD.
(2) change the data type in your table to DATETIME/SMALLDATETIME/DATE depending on accuracy required. Then `WHERE date_added >= '20110701' will work just fine (and will use an index on that column, if one exists).
(3) if you can't change the data type, then the following will work just fine as well (though no index will be used):
WHERE CONVERT(DATETIME, date_added, 101) >= '20110701'
Varchar can't be compared, try changing your column to date type.
Convert both date_added column values and your target date to DATETIME and compare; as in:
SELECT COUNT(1)
FROM Abatements_Doc
WHERE (CONVERT(datetime, date_added, 101)) >= CONVERT('07/01/2011', date_added, 101))