Split a string than join, for cast - sql

I have a table with this column
DATEFROM VARCHAR(8)
It's a string in the format 'yyyyMMdd'. I need to convert this element to Date Type.
I thought to split the string in 3 substrings (yyyy, MM, dd), than join them by adding '-' between the strings. In this way, i can cast to Date type.
How can I do it?

Repeating the answer that was posted in the question so that it doesn't show up as a question without an answer:
select cast(substring(datadal
from 1 for 4)||'-'||substring(datadal from 5 for 2)||'-'||substring(datadal from 7 for 2) AS DATE) as datadal

Related

How to select records between two dates in Access? [duplicate]

This question already has an answer here:
Query to compare between date with time and date without time - python using access db
(1 answer)
Closed 4 years ago.
I need to select records with DateTime between two dates in an Access query. The problem is that when I'm execute this query:
select * from logs
where date_added >= CDate("01/10/2018")
AND date_added <= CDate("04/10/2018")
I need both border values but the result does not include the last day. Maybe because "04/10/2018" is converted to "04/10/2018 00:00:00" and this value is less than all date_added values of that day.
Can I convert date_added to date only?
Do you can add a day to your date?
AND date_added < DateAdd('d',1,CDate("04/10/2018"))
An alternative expression:
SELECT * FROM logs
WHERE DateValue(date_added) BETWEEN #01/10/2018# AND #4/10/2018#
Useful date functions and syntax:
Date literals can be delimited with # in both VBA code and SQL statements, so you don't have to call CDate() on string values. Examples: #10/6/2018 4:16 PM#, #1/1/2018#
Simple mathematical notation can be used to add and subtract whole days from a date value. Example: #10/6/2018# + 1 == #10/7/2018#
DateValue( val ) takes arguments of various formats and returns a date/time value with only the date portion. This answers your question Can I convert date_added to date only? It essentially returns the same date value with the time portion as 00:00:00.
Example: DateValue(#10/6/2018 4:16 PM#) == #10/6/2018#
DateAdd ( interval, number, date ) as already noted by Milad Aghamohammadi.
Within SQL only (not VBA), one can use the BETWEEN operator. It works with various data types that have a natural sort order, which includes date values.
Example ... WHERE [DateField] BETWEEN #1/1/2018# AND #4/1/2018#

Find record between two dates

When I write below query it gives record .
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],[item_name],[quntity]
FROM [first].[dbo].[Purchase_Order]
WHERE order_date BETWEEN '22/04/2015' AND '4/05/2015'
In this query if I don't add 0 in '4/05/2015' it returns record.
But when I add 0 to the date i.e. '04/05/2015' it doesn't give any records.
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],[item_name],[quntity]
FROM [first].[dbo].[Purchase_Order]
WHERE order_date BETWEEN '22/04/2015' AND '04/05/2015'
The reason it's not working because SQL is trying to do a string comparison because both your types are string types, But what you really want to do a date comparison.
You should do something like this. Since you only need date part you can strip off the time and use style 103 for your format dd/mm/yyyy.
WHERE CONVERT(DATETIME,LEFT(order_date,10),103)
BETWEEN CONVERT(DATETIME,'20150422') AND CONVERT(DATETIME,'20150504')
Alternately you can use this as well if your order_date has dates like this 5/4/2015 03:20:24PM
WHERE CONVERT(DATETIME,LEFT(order_Date,CHARINDEX(' ', order_Date) - 1),103)
BETWEEN CONVERT(DATETIME,'20150422') AND CONVERT(DATETIME,'20150504')
A long term solution is to change your column order_date to DATE/DATETIME
It Better to Cast it to date rather than depend on IMPLICIT conversion
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],
[item_name],[quntity] FROM [first].[dbo].[Purchase_Order] where
convert(date,order_date,105) BETWEEN cast('22/04/2015' as Date) AND cast('04/05/2015' as date)

Date Convert varchar(10)

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

convert decimal to date during where clause [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert DB2 SQL Decimal to DATE
I have a db2 database and I want to convert a decimal to a date during the where clause in a select statement.
The decimal date could be 12 or 13 characters long depending on the month.
12 characters:
1,241,999.00 should become: 1999/1/24
13 Characters:
12,241,999.00 should become: 1999/12/24
The column name is DECIMALCOLUMN:
Select * from table1 WHERE
cast(replace(convert,DECIMALCOLUMN,date)) = #date
I see: You want some way of rearranging the digits of a number to become a date. It looks like the encoding is [m]mddyyyy. (Why isn't that a date datatype in the database?)
The number needs to be converted to a string and then substrings arranged and converted to a date. Given the complexities here, a conversion function should be written in lieu of the field being altered to be a proper datatype. Something like this should do it (untested, no access to db2):
create function decimaldate(decdate DECIMAL)
returns DATE
return
with tmp (dstr) as
(
select substr(digits (decdate),8)
from sysibm.sysdummy1
)
select
date (substr(dstr,4,4) || '-' ||
substr(dstr,1,2) || '-' ||
substr(dstr,3,2)
)
from tmp
This converts the number to a string, reformats the string as yyyy-mm-dd and converts to a date. (I used this as a basis.)
So the solution to the original question is simply to write:
SELECT *
FROM table1
WHERE decimaldate(DECIMALCOLUMN) = #date
With such a screwy way of encoding the date in the database, having the function always available should prove invaluable.

How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?

I'm sure this is quite simple, but I've been stuck on it for some time. How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?
Thanks.
Edit: I'm using Open Office Base (HSQL), not MySQL; sorry for the confusion.
Try the str_to_date and date_format functions. Something like:
select date_format( str_to_date( my_column, '%Y%c' ), '%c/01/%y' ) from my_table
try :
SELECT STR_TO_DATE(CONCAT(myDate,'01'),'%Y%m%d')
FROM myTable
Use STR_TO_DATE:
From mysql.com:
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
The date, time, or datetime values contained in str should be given in the format indicated by format. For the specifiers that can be used in format, see the DATE_FORMAT() function description. If str contains an illegal date, time, or datetime value, STR_TO_DATE() returns NULL. Starting from MySQL 5.0.3, an illegal value also produces a warning.
Range checking on the parts of date values is as described in Section 11.3.1, “The DATETIME, DATE, and TIMESTAMP Types”. This means, for example, that “zero” dates or dates with part values of 0 are allowed unless the SQL mode is set to disallow such values.
mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
-> '0000-00-00'
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Get the year:
SUBSTRING(field FROM 2 FOR 2)
Get the month:
SUBSTRING(field FROM -2 FOR 2)
Compose the date:
CONCAT(SUBSTRING(field FROM -2 FOR 2), '/01/', SUBSTRING(field FROM 2 FOR 2))
This will convert from YYYYMM to MM/01/YY.
To be clear: if you're looking for method to convert some value of type Varchar/Text to value of type Date than solutions are:
using CAST function
CAST(LEFT('201205',4)||'-'||SUBSTRING('201205' FROM 5 FOR 6)||'-01' AS DATE)
starting from OpenOffice 3.4 (HSQLDB 2.x) new Oracle-like function TO_DATE supposed to be available
TO_DATE('201205','YYYYMM')
in addition to the written i can mention that you also can construct a string with ANSI/ISO 'YYYY-MM-DD' formatted representation of the date,- Base will acknowledge that and succesfully convert it to the Date type if necessary (e.g. INSERTing in Date typed column etc.)
Here is doc's on HyperSQL and highly recommended OO Base guide by Andrew Pitonyak