query varchar field with date values - sql

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

Related

Converting a 5 digit int into time

In a legacy system (SQL Server 2005) I have a column that stores a 5 digit integer (ie 86340) as time. The legacy application shows 86340 as 23:59:00. I am unsure how how to translate that 5 digit integer into a date-time data type using SQL.
SQL Server 2012+ has TIMEFROMPARTS function:
TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
Returns a time value for the specified time and with the specified precision.
Which is similiar to Excel's TIME:
TIME(hour, minute, second)
Excel version could handle values over 0-60 range:
Minute Required. A number from 0 to 32767 representing the minute. Any value greater than 59 will be converted to hours and minutes.
And SQL counterpart cannot do that.
It looks like that value is simply number of seconds so you could use:
DECLARE #A1 INT = 86340;
SELECT DATEADD(second, #A1,CAST('00:00:00' AS TIME));
DBFiddle Demo
EDIT:
As SQL Server 2005 does not support TIME data type, you could use DATETIME instead and skip date part in application.
DECLARE #A1 INT = 86340;
SELECT DATEADD(second, #A1,CAST('00:00:00' AS DATETIME));
DBFiddle Demo2
Since the value you have is an integer representation of the seconds since midnight, you have a couple of choices in SQL Server 2005. You can either render the value as a VARCHAR, which is readable, you can render it as DATETIME, which appends the date information, or you can maybe pull in a date from another field to get an meaningful DATETIME for your value.
SELECT CONVERT(VARCHAR(12), DATEADD(SECOND, 86340, 0), 114) AS [InVarchar];
+--------------+
| InVarchar |
+--------------+
| 23:59:00:000 |
+--------------+
SELECT DATEADD(SECOND, 86340, 0) AS [InDatetime];
+-------------------------+
| InDatetime |
+-------------------------+
| 1900-01-01 23:59:00.000 |
+-------------------------+
SELECT DATEADD(SECOND, 86340, CAST('2018-09-05' AS DATETIME)) AS [InDatetimeWithDate];
+-------------------------+
| InDatetimeWithDate |
+-------------------------+
| 2018-09-05 23:59:00.000 |
+-------------------------+
USE below query:
SELECT CONVERT(DATETIME, #Column_Name)
FROM Table;

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 date format May 25 1921 12:00AM to yyyy-mm-dd

I have table with dob field as varchar datatype, i performed dateadd function on few record. Now i have few records with
May 25 1921 12:00AM format and some with yyyy-mm-dd format.
How do i set all records with same dateformat in the tableof varchar datatype?
Thanks
Simply do an update:
update your_table set dob=convert(varchar(25),cast(dob as datetime),120)
This will be the Temporary solution, I strongly recommend you to use datetime type for the datetime values. Otherwise, you will face many issues in the future.
alter table MyTable
add NewDate Date;
update MyTable
set NewDate = cast(Olddate as date);
Use Below code for convert varchar to date :
SELECT CONVERT(DATE,'May 25 1921 12:00AM',103)
Try This.
select convert(varchar(10), cast('May 25 1921 12:00AM' as date),120)
to Update :
update TableName set dob=convert(varchar(10),cast(dob as datetime),120)
from TableName

Date subtraction error

I have a SQL Server table with a few columns.
One of those columns is a date and another is No of Nights.
Number of nights is always a two character varchar column with values like 1N, 2N, 3N etc depending on the number of nights up to 7N.
I want to subtract the 1 part of the 1N column from the date.
For ex: 25Oct15 - 1N = 24Oct15
Obviously I will be replacing the '1N' with the actual column name. I tried doing a trim as:
date - left(no of nights, 1)
But I get an error
Conversion failed when converting the varchar value '25Oct16' to data type int.
Sample date below
Date | NoofNIghts | Result
2016-04-26 00:00:00.000 | 1N |
2016-04-28 00:00:00.000 | 3N |
Where the result column would be the subtracted value. Any help would be great. Thanks.
SELECT DATEADD ( DAY, - CONVERT(INT, REPLACE(NoofNights, 'N', '')), getdate() ) as Result
Try this
DECLARE #V_Date DATETIME = '2016-04-26 00:00:00.000'
,#V_NoofNIghts VARCHAR(2) = '1N'
SELECT DATEADD(DAY, CAST(LEFT(#V_NoofNIghts,1) AS INT) *-1 ,#V_Date)
Well basic query should be like
Update tablename
set result= DATEADD(d, -CAST(LEFT(NoofNIghts, LEN(NoofNIghts)-1) AS INT),Date)

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