Date Convert varchar(10) - sql

I have two tables with dates in them, the datatype in table 1 is (datetime, null). The datatype in table 2 is varchar(10). I'm trying to write a query that will match the two dates from each table and label if they are correct or not based on a macth. I have copied the query below but I always come unstuck with the convert syntax, I'm trying to get DD/MM/YYY. I would appreciate anybody's help on wrapping the correct syntax around the date columns.
Select TBL1.ID,
TBL1.AccountName,
TBL1.StartDate,
TBL2.StartDate,
CASE
WHEN LEFT(TBL1.StartDate,10) = TBL2.StartDate THEN 'Correct' ELSE 'Incorrect' END AS 'Date Check'
FROM TBL1
INNER JOIN TBL2 ON TB1.ID = TBL2.ID
GROUP BY TBL1.ID,
TBL1.AccountName,
TBL1.StartDate,
TBL2.StartDate

CONVERT(datetime,TBL1.StartDate)
instead of
LEFT(TBL1.StartDate,10)
Left will produce you a string but you need a datetime type to make the =.

Try this
CONVERT(varchar(10),Date,103) as StartDate
instead LEFT(TBL1.StartDate,10)

For correct date comparison you first need to cast varchar type to corresponding datetime representation and then convert both date dates to common format and then compare.
So change
LEFT(TBL1.StartDate,10) = TBL2.StartDate
To
CONVERT( varchar(11),TBL1.StartDate,101) = CONVERT(varchar(11),CAST(TBL2.StartDate as DATETIME),101)
Casting varchar column TBL2.StartDate to datetime will check for valid date values and throw error if invalid date value has been entered.
Also to get date columns in dd/mm/yyyy format use
Select
CONVERT(VARCHAR(11),TBL1.StartDate,103),
CONVERT(VARCHAR(11),TBL2.StartDate,103)
More detailed format list here . I suggest bookmarking it,very helpful

Related

Comparing text type date and select the greater than dates

I have a table with column(last_update_date) of data type is text.So I need to pass a date and select the greater than dates from the table.
I tried with below query,
select batch_uuid,result
from #this
where extract_status = 'success'
and last_update_date > '02/21/2019'
But above query is not working.
Any advice please.
You would need to convert both strings to dates to compare them:
select batch_uuid,result
from mytable
where
extract_status = 'success'
and to_date(last_update_date, 'mm/dd/yyyy') > to_date('02/21/2019', 'mm/dd/yyyy')
Note:
#this is not a valid table, I changed it to mytable
do consider storing dates in a date-like datatype; using a string datatype will bite you in many ways (to start with, using a function like to_date() defeats an existing index on the column)

Convert Number type to Date in postgres SQL

I have a numeric data in a column 20170930, need help in converting it into Date in PostgreSQL , tried multiple ways but non seems to work
You can convert to a string and then to a date:
select column::text::date
You can also express this using explicit cast() syntax:
select cast(cast(20170930 as text) as date)
Use one of the following :
SELECT cast(yourcol::varchar as date ) as dt1, yourcol::varchar::date as dt2
where dt1 and dt2 values of type date, and yourcol is a numeric value such as 20170930
Demo
The best thing is to change column datatype into Date type,
ALTER TABLE table_name
ADD column_name Date;
As shown above, PostgreSQL supports a full set of SQL date and time types, as shown in the table below. Dates are counted according to the Gregorian calendar. Here, all the types have a resolution of 1 microsecond / 14 digits except date type, whose resolution is day.
Please try below query
SELECT to_date(column::varchar,'YYYYMMDD')
For anybody who fell into my pitfall I tried this but my numeric was like a 'seconds past 01-01-1970 format' rather than YYYYMMDD
This worked
SELECT to_timestamp(yourcol) as numeric_column_now_date
from yourtable
see here
https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT

MM/dd/yyyy datetime data type resulted in an out-of-range value

I am inputting 2 date values in order to filter out from SQL query.
EXEC [Report].[usp_EmployeeReport_Detail] '01-01-2017','31-08-2019'
I am inputting the date as MM/dd/yyyy and the
WHERE clause contains
(j.StartDate BETWEEN #BegDate AND #EndDate)
I m getting the below error when executing the query.
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
I tried to convert the datetime result using the below way as well.
SELECT CONVERT(datetime,01-31-2017,101)
This returns 1894-05-25 00:00:00.000 as the response. How its possible?
As #Damien_The_Unbeliever has said,01-31-2017 using the Numerical expression, which evaluates to -2047.
-2047 means the day minus 2047 days from 1900-01-01, so result of date will be 1894-05-25 00:00:00.000.
So your query SELECT CONVERT(datetime,01-31-2017,101) same as SELECT CONVERT(datetime,-2047,101)
sqlfiddle
You can use the ANSI compliant format YYYYMMDD
SELECT CONVERT(datetime,'20170131',101);
instead of
DD-MM-YYYY 01-31-2017.
Or just add ' to contain the date '01-31-2017' like #fa06 answered.
Try this: u've missed the quote in date:
SELECT CONVERT(datetime,'01-31-2017',101)
try below way
SELECT CONVERT(CHAR,GETDATE(),1 )
it returns 08/13/18
in your case you missed the quote as a result output that type shown

Find rows in SQL that with date when it is stored as datetime?

My problem is this (using SQL Server 2008 R2).
There is some date columns with types as datetime.
So the original intention with the column was to store a date without any time.
Then datetime was chosen as datatype.
Sure it works but as the database is also logically connected to a UML-diagram I want to use the right datatype.
An example the column Parcel.DateofArrival has the type datetime.
There maybe rows that are
2011-08-05 00:00:00.000
this is a date. But if there is rows like
2011-08-05 07:30:00.000
it is a datetime.
Now I want to find a query that list rows only containing dates, not datetime.
Any hint ?
An easy way to do this is:
select p.*
from Parcel p
where DateOfArrival = cast(DateOfArrival as Date);
By casting the value to a date, the datetime portion is lost. If the original value equals this, then there is no time component.
A way to do this would be to convert it in your select statement, for example:
SELECT CONVERT(DATE, DateOfArrival) Date, *other columns*
FROM Parcel P
Another solution, would be converting it to VARCHAR, formatting it in a yyyyMMdd format, like:
SELECT CONVERT(VARCHAR(8), DateOfArrival, 112) Date, *other columns*
FROM Parcel P
And if you want to sort it or group it, you have to use the conversion.
I hope it was helpful!
select p.*
from Parcel p
where cast(DateOfArrival as time) = '00:00'

Convert NVARCHAR to DATETIME and select distinct Year

SELECT DISTINCT YEAR(convert(varchar(max),OrderCreatedDate)) from webshop
The above sql query is producing this error:
Conversion failed when converting date and/or time from character string.
The value in the database is NVARCHAR and in the following format: DD/MM/YYYY 00:00:00 AM (/PM)
I would like to select the unique values for the year only!
thanks for any help
To avoid this sort of issues, date should be saved in DateTime type field Not in a string field.
Year() function parameter is a DateTime type not a String. So you should make sure that the string you are passing is convertible to a DateTime type. In this case you could trim out the time part with Left() function and use 103 style as below.
Fiddle demo:
--Example
declare #val nvarchar(50) = '28/10/2013 11:25:45 AM (/PM)'
select year(convert(date,left(#val,10),103)) myYear
--Applying to your query
SELECT DISTINCT Year(Convert(Date,Left(OrderCreatedDate,10),103)) FROM Webshop
UPDATE:
If you are getting errors, it could be due to your date format. i.e. Format of the string you have saved may not be as you have described (DD/MM/YYYY 00:00:00 AM (/PM)) in the question.
Please check with ISDATE() function before converting to date and identify which records are causing the problem and correct them.
Try this query to get all of them with invalid strings. Following query will return 0 for values with invalid formatting.
SELECT DISTINCT CASE WHEN IsDate(eft(OrderCreatedDate,10))=1 THEN
Year(Convert(Date,Left(OrderCreatedDate,10),103))
ELSE 0 END as myDate,
OrderCreatedDate
FROM Webshop
Or you could get only the records which are causing the problem as;
SELECT OrderCreatedDate
FROM Webshop
WHERE IsDate(Left(OrderCreatedDate,10)) = 0
select distinct year(CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105)))
Try this
SELECT DISTINCT YEAR(Convert(datetime,OrderCreatedDate,103)) from webshop
DD/MM/YYYY 00:00:00 AM (/PM) is the British format. See Convert