Select most recent records by DB2 date in form of YYYYMMDD - sql

I am importing records from a DB2 data source into a MS SQL Server destination.
The records are coming in with the date format of 20150302/YYYYMMDD, but I only want the last 14 days based on current server date.
Can some advise on how to select based on this date format against DATEADD(d, - 1, { fn CURDATE() }) please.
Thanks!

It would be better to do this on the DB2 side, to reduce the number of records brought over.
Additionally, it's better from a performance standpoint to convert the static date into a numeric date and compare to the column in your table. Rather than convert the numeric date in your table to a actual date type for comparison.
where numdate >= int(replace(char(current_date - 14 days,iso),'-',''))
Doing it this way will allow you to take advantage of an index over numdate. In addition, DB2 will only need to perform this conversion once.
Depending on your platform & version, you may have an easier way to convert from a date data type to a numeric date. But the above works on DB2 for i and should work on most (all?) DB2 versions and platforms.
You may find it worthwhile to create a UDF to do this conversion for you.

If you want logic in SQL Server, then you are in luck, because you can just convert the YYYYMMDD format to a date:
where cast(datecol as date) >= cast(getdate() - 14 as date)
(This assumes no future dates.)
If you want to do this on the DB2 side, you can use to_date():
where to_date(datecol, 'YYYYMMDD') >= current date - 14 days

Related

Unable to get data between two years

I am not getting data between two years, below is between condition
to_char(Wfc.APPLYDTM,'MM/DD/YYYY') between '12/11/2019' and '01/10/2020'
but I am getting data between '12/11/2019' and '12/31/2019' & '01/11/2020' and '01/01/2020' for these dates but not between two different years.
Please help
Try using TO_DATE instead of TO_CHAR, and then compare against valid Oracle date literals:
SELECT *
FROM Wfc
WHERE TO_DATE(APPLYDTM, 'MM/DD/YYYY') BETWEEN date '2019-12-11' AND date '2019-01-10';
Note that if APPLYDTM already be a date, then you don't need to call TO_DATE on it. It doesn't make sense to convert your data to character, if you intend to work with it as a date.
You should convert your data to Date to be able to compare correctly.
The main idea is you should compare date value instead of string value.
to_date(Wfc.APPLYDTM,'MM/dd/yyyy') between to_date('12/11/2019','MM/dd/yyyy') and to_date('01/10/2020','MM/dd/yyyy')
Read here to more details.
Do not convert date/time values to strings! Use the built in functionality.
Your logic is most simply expressed as:
Wfc.APPLYDTMbetween >= DATE '2019-12-11' AND
Wfc.APPLYDTMbetween < DATE '2020-01-11'
Note that the date constants are provided using the DATE keyword. This supposed ISO 8601 standard date formats (happily!).
Also note the use of >= and < rather than BETWEEN. The date data type in Oracle can include a time component -- even if you don't see it when you query the table. This ensures that all date/times are included in the range.
As an added benefit, this can use an index on (APPLYDTMbetween). Using a function usually precludes using an index, unless you have defined a function-based index.

SQL query to bring back list of servers from specific date range

I'm trying to make a query with SQL Server Management Studio 2017 that brings back a count of all the servers with a projected migration date of this year. I have one query made now, but it's still bringing back some servers with dates from years before.
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >='01/01/2019' AND Projected <='12/31/2019
GROUP BY Month(Projected)
ORDER BY [Month]
Date format is mm/dd/yyyy btw. How can I get this query to bring back just servers that are projected for the year 2019?
Going by the assumption that your data type is wrong, the first step is to fix that.
Note, I am assuming that your data only contains dates, and not time (which your query implies). Firstly, you'll need to change the value of all your rows to an convertible value, we'll go with the ISO format yyyyMMdd:
UPDATE dbo.tFake
SET Projected = CONVERT(varchar(8),CONVERT(date,Projected,101),112);
Now that all the rows are a literal string in the format yyyyMMdd we can alter the column:
ALTER TABLE dbo.tFake ALTER COLUMN Projected date;
Now, we can run your query again, but now your data type is correct, you won't have the problem:
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >= '20190101' AND Project < '20200101' --I prefer the >= and < method. This is especially import with date & time data types
GROUP BY Month(Projected)
ORDER BY [Month];
Notice the literal strings I passed are also in the yyyyMMdd format. If you must pass a literal string in the format MMddyyyy you can wrap in a CONVERT with the style code 101: CONVERT(date,'12/31/2019',101). 101 means the US style date (CAST and CONVERT (Transact-SQL).
Remember, this solution assumes you have date only values, and not date and time values. If you do (have date and time values) you'll want to use an appropriate date and time data type and use the ISO8601 style, instead of the ISO style.

DB2 Convert Number to Date

For some reason (I have no control over this) dates are stored as Integers in an iSeries AS400 DB2 system that I need to query. E.g. today will be stored as:
20,171,221
Being in the UK I need it to be like the below in Date format:
21/12/2017
This is from my query: (OAORDT = date field)
Select
Date(SUBSTR( CHAR( OAORDT ),7,2) ||'/' || SUBSTR(CHAR ( OAORDT ),5,2) || '/' || SUBSTR(CHAR (OAORDT ),1,4)) AS "Order Date"
from some.table
However, all I get is Nulls. If I remove the Date function, then it does work but its now a string, which I don't want:
Select
SUBSTR( CHAR( OAORDT ),7,2) ||'/' || SUBSTR(CHAR ( OAORDT ),5,2) || '/' || SUBSTR(CHAR (OAORDT ),1,4) AS "Order Date"
from some.table
How do I convert the OAORDT field to Date?
Just to update - I will be querying this from MS SQL Server using an OpenQuery
Thanks.
1) How do I convert the OAORDT field to Date?
Simplest is to use TIMESTAMP_FORMAT :
SELECT DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD'))
2) Being in the UK I need it to be [...] in Date format 21/12/2017 :
SELECT VARCHAR_FORMAT(DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD')),'DD/MM/YYYY')
Note, you didn't specify where you are doing this, but since you tagged as ibm-midrange, I am answering for embedded SQL. If you want JDBC, or ODBC, or interactive SQL, the concept is similar, just the means of achieving it is different.
Make sure SQL is using dates in the correct format, it defaults to *ISO. For you it should be *EUR. In RPG, you can do it this way:
exec sql set option *datfmt = *EUR;
Make sure that set option is the first SQL statement in your program, I generally put it immediately between D and C specs.
Note that this is not an optimal solution for a program. Best practice is to set the RPG and SQL date formats both to *ISO. I like to do that explicitly. RPG date format is set by
ctl-opt DatFmt(*ISO);
SQL date format is set by
exec sql set option *datfmt = *ISO;
Now all internal dates are processed in *ISO format, and have no year range limitation (year can be 0001 - 9999). And you can display or print in any format you please. Likewise, you can receive input in any format you please.
Edit Dates are a unique beast. Not every language, nor OS knows how to handle them. If you are looking for a Date value, the only format you need to specify is the format of the string you are converting to a Date. You don't need to (can't) specify the internal format of the Date field, and the external format of a Date field can be mostly anything you want, and different each time you use it. So when you use TIMESTAMP_FORMAT() as #Stavr00 mentioned:
DATE(TIMESTAMP_FORMAT(CHAR(OAORDT),'YYYYMMDD'))
The format provided is not the format of the Date field, but the format of the data being converted to a Timestamp. Then the Date() function converts the Timestamp value into a Date value. At this point format doesn't matter because regardless of which external format you have specified by *DATFMT, the timestamp is in the internal timestamp format, and the date value is in the internal date format. The next time the format matters is when you present the Date value to a user as a string or number. At that point the format can be set to *ISO, *EUR, *USA, *JIS, *YMD, *MDY, *DMY, or *JUL, and in some cases *LONGJUL and the *Cxxx formats are available.
Since none of variants suited my needs I've came out with my own.
It is as simple as:
select * from yourschema.yourtable where yourdate = int(CURRENT DATE - 1 days) - 19000000;
This days thing is leap year-aware and suits most needs fine.
Same way days can be turned to months or years.
No need for heavy artillery like VARCHAR_FORMAT/TIMESTAMP_FORMAT.
Below worked for me:
select date(substring(trim(DateCharCol), 1, 2)||'/'||substring(trim(DateCharCol), 3, 2)||'/'||'20'||substring(trim(DateCharCol), 5, 2)) from yourTable where TableCol =?;

T-SQL Dates using Convert() function?

I am bit confusing here?
declare #date1 datetime = '2016-01-21 14:10:47.183'
I want to convert '2016-01-21 14:10:47.183' To '21-01-2016'
when I tried: select convert(date,#date1,105)
I am getting: 2016-01-21
But with: select convert(varchar(10),#date1,105)
I am getting: 21-01-2016
Why I am not having same results with above code?
Why should I convert to varchar?
Thanks in advance
This is just presentation matter and should be done in application layer. If you cannot do it in application you could use FORMAT (SQL Server 2012+):
declare #date1 datetime = '2016-01-21 14:10:47.183'
SELECT FORMAT(#date1, 'dd-mm-yyyy');
LiveDemo
Why I am not having same results with above code?
select convert(date,#date1,105)
-- DATETIME -> DATE
-- vs
select convert(varchar(10),#date1,105)
-- DATETIME -> VARCHAR(10) using specific style
If you only to skip time part use SELECT CAST(#date1 AS DATE) and do not bother how it is presented. It is still DATE.
To sum up: in SQL query use DATE as date, in application display it with desired format.
The reason why is because once you put a value in a datetime column (or date or any of the other variations on date-time datatypes) in SQL Server. SQL Server ceases to think of that date as having any particular format. It translates it into numbers, and stores it that way internally.
So when you select a date from a date time column, SQL Server displays it in the default format that you have selected based on your environment/local settings.
If you want to display it in any other format, you have to first convert it to a string, because as far as SQL Server is concerned, dates don't have formats. They are just numbers. The 21st day of March is the 21st day of March, whether you write it as 3/21 or 21/3.
So when you try to convert a date to a date with a different format, SQL Server just ignores you because dates don't have formats. However, if you want to convert that date to a string, SQL Server will be happy to help you display that string in any format you like.
Hope this helps, but sounds like some further research into how SQL Server stores dates would help your understanding.

Issue querying date from oracle.

I understand that querying a date will fail as its comparing a string to date and that can cause an issue.
Oracle 11.2 G
Unicode DB
NLS_DATE_FORMAT DD-MON-RR
select * from table where Q_date='16-Mar-09';
It can be solved by
select * from table where trunc(Q_date) = TO_DATE('16-MAR-09', 'DD-MON-YY');
What I don't get is why this works.
select* from table where Q_date='07-JAN-08';
If anyone can please elaborate or correct my mindset.
Thanks
Oracle does allow date literals, but they depend on the installation (particularly the value of NLS_DATE_FORMAT as explained here). Hence, there is not a universal format for interpreting a single string as a date (unless you use the DATE keyword).
The default format is DD-MM-YY, which seems to be the format for your server. So, your statement:
where Q_date = '07-JAN-08'
is interpreted using this format.
I prefer to use the DATE keyword with the ISO standard YYYY-MM-DD format:
where Q_Date = DATE '2008-01-07'
If this gets no rows returned:
select * from table where Q_date='16-Mar-09';
but this does see data:
select * from table where trunc(Q_date) = TO_DATE('16-MAR-09', 'DD-MON-YY');
then you have rows which have a time other than midnight. At this point in the century DD-MON-RR and DD-MON-YY are equivalent, and both will see 09 as 2009, so the date part is right. But the first will only find rows where the time is midnight, while the second is stripping the time off via the trunc, meaning the dates on both sides are at midnight, and therefore equal.
And since this also finds data:
select* from table where Q_date='07-JAN-08';
... then you have rows at midnight on that date. You might also have rows with other times, so checking the count with the trunc version might be useful.
You can check the times you actually have with:
select to_char(q_date, 'YYYY-MM-DD HH24:MI:SS') from table;
If you do want to make sure you catch all times within the day you can use a range:
select * from table where
q_date >= date '2009-03-16'
and q_date < date '2009-03-17';
Quick SQL Fiddle demo.
Although it sounds like you're expecting all the times to be midnight, which might indicate a data problem.