Converting Varchar to Date and date Comparison - sql

I am converting two Date columns to find the most recent one
SELECT ISNULL(CONVERT(varchar(10),REPLACE('10-07-2015','/','-'), 103),'01-01-1900'),
ISNULL(CONVERT(varchar(10),REPLACE('10/7/2015','/','-'), 103),'01-01-1900'),
CASE
WHEN ISNULL(CONVERT(varchar,REPLACE('10-07-2015','/','-'), 103),'01-01-1900') = ISNULL(CONVERT(varchar,REPLACE('10/7/2015','/','-'), 103),'01-01-1900')
THEN '10-07-2015'
END
My issue is some dates missing leading Zero in Day or Month and comparison is giving false results. Is there a better way to handle this? Other issue is one column has date with '/' and other have with '-'
Currently case is only checking on '=' but will add more to get the most recent

You can just convert those 2 varchars to the DATE type, then compare them.
You can find the date/datetime styles here
For those DD/MM/YYYY datestamps the 103 style would fit.
And to calculate the most recent between them, just wrap it in a CASE.
Example snippet:
declare #T table (
id int identity(1,1) primary key,
datestamp1 varchar(10),
datestamp2 varchar(10)
);
insert into #T (datestamp1, datestamp2) values
('5/9/2018','17/9/2018')
,('9-10-2018','16-10-2018')
,('15-10-2018','13-10-2018')
;
SELECT *,
TRY_CONVERT(DATE, datestamp1, 103) as date1,
TRY_CONVERT(DATE, datestamp2, 103) as date2,
CASE
WHEN TRY_CONVERT(DATE, datestamp1, 103) >= TRY_CONVERT(DATE, datestamp2, 103) THEN datestamp1
WHEN TRY_CONVERT(DATE, datestamp2, 103) IS NULL THEN datestamp1
ELSE datestamp2
END AS MostRecentDatestamp
FROM #T;
Returns:
id datestamp1 datestamp2 date1 date2 MostRecentDatestamp
1 5/9/2018 17/9/2018 2018-09-05 2018-09-17 17/9/2018
2 9-10-2018 16-10-2018 2018-10-09 2018-10-16 16-10-2018
3 15-10-2018 13-10-2018 2018-10-15 2018-10-13 15-10-2018

Related

Convert varchar to date without timestamp

I am trying to convert/select the nvarchar datatype to date format (YYYY-MM-DD).
The table contains the date in DD/MM/YYYY format & also the null values.
Below SQL query is working fine but it has timestamp in the output
select Date4 = Convert(datetime, Last_Paid_Date, 103) FROM table
2021-01-30 00:00:00.000
My requirement is to have only the date in (YYYY-MM-DD) format
normally this should work
select Convert(date, Last_Paid_Date, 103) from tablename
But if you get conversion errors you can try this
SELECT convert(date, convert(datetime, Last_Paid_Date, 103)) FROM TableName
if Date cannot be used to convert from your format, the trick is to convert to a datetime first, and then convert that into a date.
Much much better would be to store the data in a column with type Date instead of varchar off course
I find this also some good reading
EDIT
if you keep getting conversion errors, then probably there are invalid dates in your varchar column. That is why you should never never never store dates/time in a varchar column.
To fix this, you could use this
SELECT try_Convert(date, Last_Paid_Date, 103) from tablename
this will put NULL in all columns that have an invalid date/time.
Drawback is that from all the rows that will have a value NULL, you cannot know if the original value was also NULL or an invalid date/time value.
Please try the below.
SELECT Date4 = CONVERT(DATE, Last_Paid_Date, 103) FROM TableName
OR
SELECT Date4 = CAST(GETDATE() AS DATE) FROM TableName
This will remove the Timestamp and give you only the Date values in the (YYYY-MM-DD) format.
You can go for simple conversion.
SELECT Convert(date, '20/01/2020', 103)
2020-01-20
You can go for conversion for the table as given below:
SELECT Convert(date, val, 103) as dateval FROM
(
values
('20/01/2020'),(null)
) as t(val)
dateval
2020-01-20
NULL
The issue with your query is that the column: "Last_Paid_Date" contains NULL String, which needs the conversion as they are characters.
You can try the below query:
SELECT convert(date, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
, convert(datetime, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
FROM table
The query will replace the NULL strings with a default value if any and then do the date/datetime conversions accordingly
You can chain two conversions : the first one converts the original dd/mm/yyyy (103) to a datetime value, and the second conversion turns that datetime into a yyyy-mm-dd (120) string.
select Date4 = convert(varchar(10), convert(date, Last_Paid_Date, 103), 120)
from table

error executing a query with date check in where clause

I have a table with year and month values saved as int datatype columns [Year] and [Month] correspondingly. I need to query the table limiting the output by a certain date using WHERE clause. I came up with a solution using DATEFROMPARTS function (avoids multiple conversions of datatypes), which works perfectly in the SELECT clause (the number of distinct dates is limited so I can check all of them), but fails when I am trying to use the composite date in a WHERE clause.
Thus query like
SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable
gives
2019-04-01
2019-05-01
2019-06-01
2019-07-01
2019-08-01
2019-09-01
2019-10-01
2019-11-01
2019-12-01
2020-01-01
2020-02-01
2020-03-01
but when I add a WHERE clause like
SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable
WHERE DATEFROMPARTS([Year], [Month], 1) < convert(date, getdate(), 23)
or
SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1) FROM MyTable
WHERE DATEFROMPARTS([Year], [MonthNumber], 1) < convert (date, '2019-12-01', 23)
I get an error:
Cannot construct data type date, some of the arguments have values which are not valid.
I am using SQL Server Ver. 13
DISCLAIMER
The data is stored on a remote SQL server I am accessing from a cloud machine. It is a view, I have zero permissions on, only to read and use it further in an ETL process. There are no illegal values in Year and Month columns like NULL, Month > 12, etc.
UPDATE
I have tried a similar scenario on an SQL Server 2016:
CREATE TABLE MyTable(
[Year] [int] NULL,
[Month] [int] NULL)
INSERT INTO MyTable
([Year], [Month])
VALUES
(2019, 9)
,(2019, 10)
,(2019, 11)
,(2019, 12)
,(2020, 1)
,(2020, 2)
,(2020, 3)
,(2020, 4)
A combination of DATEFROMPARTS or concatenating dateparts and converting to date of different formats does not work, at the best, the date only looks ok with yyyy-mm-dd format, but fails to compare with a getdate() function.
The Solution suggested by #John-Cappelletti helped to solve the initial problem:
try_convert(date, concat([Year],'/',[Month],'/', 1))
although it still unclear to me why it is not possible to convert the combined date into different date styles.
Due to a data issue, perhaps use try_convert() with a concat()
Example
Declare #YourTable Table ([Year] int,[Month] int)
Insert Into #YourTable Values
(2020,1)
,(2020,1)
,(2020,2)
,(2020,222)
Select *
,try_convert(date,concat([Year],'/',[Month],'/', 1))
From #YourTable
Returns
Year Month (No column name)
2020 1 2020-01-01
2020 1 2020-01-01
2020 2 2020-02-01
2020 222 NULL << There's a problem
Leave off the 23:
WHERE DATEFROMPARTS([Year], [Month], 1) < convert(date, getdate())
You probably have an issue with the internationalization settings. Your version is converting getdate() to a string and back to a date.
DATEFROMPARTS(YEAR,MONTH,DAY) will return a value in a DATE format.
Simply CAST the parameter you're wanting to compare it to in the same format. Then are you comparing the same type of formats.
The error you've previously got is because you're trying to convert to different data types.
SELECT DISTINCT DATEFROMPARTS([Year], [Month], 1)
FROM MyTable
WHERE DATEFROMPARTS([Year], [Month], 1) < CAST(GETDATE() as DATE)

SQL Server date time convert

I have a field in my database table called Month which holds its values as an INT it has the values 1 to 12 - I would like a way to convert 1 to read 1-11-2016 00:00:00 ie as a datetime field, 2 to read 1-12-2016 00:00:00, 3 to read 1-1-2017 00:00:00 - how can I convert a value like this? I am ok with doing case to switch but the convert/cast is confusing me...
You need to define a startdate (either by parameter or in a CTE), then just use dateadd()
#StartDate = '2016-10-01 00:00:00'
select dateadd(mm, t1.month, #StartDate) as NewMonth
from MyTable t1
Another response is
SELECT CONVERT(DATE, '2016-' + CAST(id AS VARCHAR(2)) + '-01') AS myDate
FROM T1
But y prefer JohmHC answer !!

Convert Decimal or Varchar into Date

I have 2 fields.
Birth= Datatype Decimal(12,4) & Date = Datatype Date
Birth Date
19650101 2015-07-09
how do i get a result that looks like this
i want the result to be like this
Birth Date
1965-01-01 2015-07-09
where the Birth is a Date datatype and not a decimal (12,4)
To convert the number 19650101 to a date use
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)
To get the number of years (to one decimal) you could do:
ROUND(
DATEDIFF(day,
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
[Date])/365.25
,1)
Which won't be exact but should be close enough to tenths of a year.
You can use this:
-- Create demo data
CREATE TABLE #dates(birth int, date date)
INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')
-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date,
DATEDIFF(year,
CONVERT(date,CONVERT(nvarchar(max),birth),112),
date
) as years
FROM #dates
-- Cleanup
DROP TABLE #dates
This depends on the exact format you provides (19650101).
Here is one way to do this conversion.
cast(cast(FLOOR(birth) as CHAR(8)) as DATE)
I think you don't need to round. Just convert your decimal value and put "-" like below : )
select left(birth,4) +'-' +
substring(convert(nvarchar,birth),5,2)+'-'+
substring(convert(nvarchar,birth),7,2)

only date and only time in same column - sql server

I have a web portal that should display only time if the date is today's date otherwise it should display date .
dossier_date_created | Expected result
----------------------------------------------------
2013-10-22 16:18:46.610 | 2013-10-22
2013-10-23 11:26:56.390 | 11:26
I tried something like this :
select
case
when CONVERT(date,dossier_date_created) = CONVERT(DATE,getdate()) then convert(char(5), dossier_date_created, 108)
else convert(date, dossier_date_created)
end as timedate
from Proj_Manage_Dossier
But the result was :
timedate
-----------
2013-10-22
1900-01-01
How can I do it only with SQL? And btw Datatype of my column "dossier_date_created" is datetime
You can just use CAST or CONVERT to get your values to DATE or TIME datatypes. But, since you can't combine two data types in same column you have to cast them both to something identical - like NVARCHAR afterwards:
SELECT CASE WHEN CAST(dossier_date_created AS DATE) = CAST(GETDATE() AS DATE)
THEN CAST(CAST (dossier_date_created AS TIME) AS NVARCHAR(10))
ELSE CAST(CAST(dossier_date_created AS DATE) AS NVARCHAR(10)) END
FROM dbo.Proj_Manage_Dossier
SQLFiddle DEMO
EDIT - For SQL Server versions older then 2008, where there are no DATE and TIME datatypes - You can also directly CONVERT to VARCHAR using appropriate style codes.
SELECT CASE WHEN CONVERT(VARCHAR(10),dossier_date_created,102) = CONVERT(VARCHAR(12),GETDATE(),102)
THEN CONVERT(VARCHAR(10),dossier_date_created,108)
ELSE CONVERT(VARCHAR(10),dossier_date_created,102) END
FROM dbo.Proj_Manage_Dossier
SQLFiddle DEMO
This works fine for me:
select
case
when (CONVERT(date,PaymentDate) = CONVERT(DATE,getdate()))
then convert(VARCHAR(15), PaymentDate, 108)
else convert(varchar, PaymentDate, 101)
end as timedate
from Payments
Hope it will help you.. :)
This will work
select case when cast(dossier_date_created as date) = cast(getdate() as date)
then cast(cast(dossier_date_created as time) as varchar)
else cast(cast(dossier_date_created as date) as varchar)
end from #Proj_Manage_Dossier
Hope it helps :)
cheers......