replace string with date value - sql

Currently, I have a Derived Column transformation within my package that will look for a NULL value and if it is NULL it will give it a default date with forwarding slashes as seen below
REPLACENULL([date],"2/2/1999")
However, if that field is Not NULL it will have a string date which will look like 20200202. I am wanting to add on to the current expression to where if the field is not null that it replaces 20200202 with 2020-02-02. I would appreciate the help and will rate it highly!

Here's how I would do that in SQL Server.
Note: FORMAT requires SQL Server 2012+
DECLARE #StringDate varchar(20);
-- NON-NULL date.
SET #StringDate = '20200202'
SELECT
ISNULL ( FORMAT( CAST ( #StringDate AS date ), 'yyyy-MM-dd' ), '2/2/1999' ) AS NonNullStringDate;
-- NULL date.
SET #StringDate = NULL;
SELECT
ISNULL ( FORMAT( CAST ( #StringDate AS date ), 'yyyy-MM-dd' ), '2/2/1999' ) AS NullStringDate;
Returns (respectively)
+-------------------+
| NonNullStringDate |
+-------------------+
| 2020-02-02 |
+-------------------+
+----------------+
| NullStringDate |
+----------------+
| 2/2/1999 |
+----------------+
For date formatting consistency, you may want to consider changing 2/2/1999 to 1999-2-2.

First of all, you should use 1999-02-02 as a default value to make sure that all values are stored in the same format. The following expression will convert the date format from yyyyMMdd to yyyy-MM-dd:
REPLACENULL([date],"") == "" ? "1999-02-02" : LEFT([date],4) + "-" + SUBSTRING([date],5,2) + "-" + RIGHT([date],2)

Related

Convert custom format string to Date

I'm receiving date values(as string) from one of the source system. It is always a 8 char long as shown below. I'm really not sure why they have kept in this format.
15/06-10
07/03-03
28/10-04
10/07-90
05/07-55
But for my application, I need to convert this into a proper date format(i.e. DD-MON-YYYY).
First 2 characters represent Date
Next 2 characters(after /) represent Month
last 2 represent year
In oracle, I can use to_date to achieve this. Something like
select to_date('15/06-10','yy/mm-dd') from dual;
But in SQL Server, I couldn't find such function. Is there a way to achieve this? The closest I have got is
DECLARE #d VARCHAR(100) = '15/06-10';
SELECT DATEFROMPARTS('20'+SUBSTRING(#d,7,2),SUBSTRING(#d,4,2),SUBSTRING(#d,1,2))
I'm not sure if this is the right way. Also It is giving the results only when I hardcode 20 for the year. But i'm getting data from 1950. So I cannot hardcode 19 or 20 Expected output for above sample is
+----------+-------------+
| 15/06-10 | 15-JUN-2010 |
+----------+-------------+
| 07/03-03 | 07-MAR-2003 |
+----------+-------------+
| 28/10-04 | 28-OCT-2004 |
+----------+-------------+
| 10/07-90 | 10-JUL-1990 |
+----------+-------------+
| 05/07-55 | 05-JUL-1955 |
+----------+-------------+
SQL Server does not have a to_date() function. But here is a simpler way to do the conversion you want:
select convert(date, replace('20' + str, '/', '-'))
from (values ('15/06-10'), ('07/03-03'), ('28/10-04')) v(str)
The expression in the select actually changes the format to YYYY-MM-DD, which is trivially converted to a date. However, SQL Server convert()/cast() is relatively smart about recognizing dates in strings.
One option uses datefromparts() and string functions:
select datefromparts(
'20' + left(#d, 2),
substring(#d, 4, 2),
right(#d, 2)
) as dt

query varchar field with date values

on sql-server db i need to query the dates > getdate from a varchar field
My table is like below ( activatioDate type is varchar(100)) :
id | activatioDate
22 | 12/3/2021
23 | 12/7/2019
24 | 12/9/2020
25 | 12/3/2019
26 | 12/11/2019
27 | 12/1/2024
my query
select * from mytable
where activatioDate > GETDATE()
Expected result
22 | 12/3/2021
24 | 12/9/2020
27 | 12/1/2024
I've got the following error
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. "
Any suggestion?
You need to fix your design; that's the real problem here. Firstly, change the values to a unambiguous date/time format:
UPDATE dbo.YourTable
SET activatioDate = CONVERT(varchar(8),CONVERT(date,activatioDate,101),120);
Then you can ALTER the table:
ALTER dbo.YourTable ALTER COLUMN activatioDate date;
And then, finally, your query will work:
SELECT *
FROM dbo.YourTable
WHERE activatioDate > GETDATE();
Use CONVERT:
SELECT *
FROM mytable
WHERE CONVERT(datetime, activatioDate, 101) > GETDATE();
But in general you should avoid storing your dates as text in your SQL database.
Find all employees who didn't make any orders in the past 6 months. Tricky thing - the date field is varchar. You need to cast it to Date and apply Date functions

SQL query for displaying year from date table

I am creating a table of random dates with varchar(200) data type and I am unable to generate my query of getting displayed date where year > 2000
ex:
12/03/2017
12/02/1998
12/11/2002
First, you should not be storing dates as strings. It is a bad idea to store fields in the wrong type.
Second, if you do have to store dates as strings (which is occasionally necessary), then use the ISO standard formats: YYYY-MM-DD or YYYYMMDD.
For the format that you are using, you can extract the last four characters:
select right(DateWronglyStoredInStringColumn, 4) as yyyy
You should be storing your dates as a date or datetime2 or datetime datatype in sql server.
For sql server versions prior to sql server 2012, try just using convert():
For dates where the day is first, use set dateformatdmy;
set dateformat dmy;
select
year(convert(date,randomDate)) as [Year]
, randomDate
from t
where year(convert(date,randomDate)) > 2000;
For sql server 2012+, you could use try_convert():
set dateformat dmy;
select
year(try_convert(date,randomDate)) as [Year]
, randomDate
from t
where year(try_convert(date,randomDate)) > 2000;
rextester demo: http://rextester.com/DXVR82331
create table a ( date varchar(200) );
insert into a values
('13-09-2017')
,('12-12-1987')
,('27-01-2037')
,('22-04-1877')
,('02-11-1987')
,('16-08-1974');
set dateformat dmy;
select convert(date,a.[date]) as date
from a
where year(convert(date,a.[date])) > 2000;
returns:
+---------------------+
| date |
+---------------------+
| 13.09.2017 00:00:00 |
| 27.01.2037 00:00:00 |
+---------------------+
Try
select date
from a where convert(char(4),date,121) > '2000'
But be careful when you sort or order the year as You use varchar (text).
Might want to convert the year to an integer for that purpose.

How to convert string ddmmyyyy to datetime fomat (DD/MM/YYYY) from provider IBMDA400

I have a problem when I try converting data from column name:'date'(string: ddmmyyyy ex:09032015) to fomat datetime (DD/MM/YYYY) and I'm using provider IBMDA400.
I use some commands to try converting but have not been successful.
My purpose is only select data from database but Visual Studio always displays error.
ex:
Cmd1: select date(to_date(my string,'dd/mm/yyyy') from table
-> In here appear error: SQ20448: Expression not valid using format string specified for TIMESTAMP_FORMAT.
And I changed: 'TIMESTAMP_FORMAT' instead of 'TO_DATE'
cmd2: select TIMESTAMP_FORMAT(mystring, 'DD/MM/RRRR HH24:MI')
-> Error SQ20448 continue to occur.
you have indicated through comments below that there are 3 string fields (for day, month and year) and that you concatenate these so they look like 09032015
Instead concatenate in an ISO standard fashion and then convert to date.
For DB2 I would try this:
to_date( ( CONCAT z CONCAT '-' CONCAT Y CONCAT '-' CONCAT X) , 'YYYY-MM-DD' )
where
Z = year string
Y = month string
x = day string
Once you have a date you can reformat it to any desired style you like.
Please note that date data types are NOT STORED in any particular format.
This following was prepared on the (wrong) assumption of the dbms being Oracle.
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE TABLE1
(X date, Y timestamp, Z varchar2(60))
;
INSERT ALL
INTO TABLE1 (X,Y,Z)
VALUES (to_date('09032015','ddmmyyyy'), to_timestamp('09032015','ddmmyyyy'), '09032015')
SELECT * FROM dual
;
Query 1:
SELECT
TO_CHAR(X, 'DD/MM/YYYY')
, TO_CHAR(Y, 'DD/MM/YYYY')
, substr(Z,1,2) || '/' || substr(Z,3,2) || '/' || substr(Z,5,4)
FROM TABLE1
Results:
| TO_CHAR(X,'DD/MM/YYYY') | TO_CHAR(Y,'DD/MM/YYYY') | SUBSTR(Z,1,2)||'/'||SUBSTR(Z,3,2)||'/'||SUBSTR(Z,5,4) |
|-------------------------|-------------------------|-------------------------------------------------------|
| 09/03/2015 | 09/03/2015 | 09/03/2015 |

How to convert decimal to date?

I have a problem. I have a field START_VALUE where the data type is decimal. I want to convert Decimal to Date.
The data type START_VALUE is Decimal.The data of START_VALUE is :
START_VALUE
|=========|
| 240368 |
| 198448 |
| 197396 |
| 126743 |
I want to convert to Datetime and what i want to expect is like 'yyyy-mm-dd 00:00:00.000'
I don't know if the value is Julian date or else. Please help me to find the right select query.
Thanks.
Are you looking for this
CREATE FUNCTION Number_To_Date(No_Of_Days NUMBER)
RETURN DATE IS
BEGIN
RETURN to_date('1899-12-30', 'YYYY-MM-DD') + No_Of_Days;
END;
You can use the following query in SQL Server to parse it to datetime
SELECT CONVERT(DATETIME, SUBSTRING(CAST(START_VALUE
as varchar(8)),1,2) + '-' + SUBSTRING(CAST(START_VALUE
as varchar(8)),3,2) + '-' + SUBSTRING(CAST(START_VALUE
as varchar(8)),5,2),5) AS DateTimeValue
FROM Table
If you are using Oracle then you can use the following query
SELECT TO_DATE(CAST(START_VALUE AS VARCHAR(8), 'DDMMYY') FROM Table