I'm new to SQL Server and I would like to know how to convert data types in SQL Server. As far as I know SQL Server doesn't support format mask (ex.'YYYY-MM-DD' or '999'). It's basically about all data types, not only DATE
data type as below.
Let's say that I want to convert '20240512' to 2024-12-05, NOT default one: 2024-05-12.
In Oracle I can use TO_DATE and CAST - both functions support mask.
SELECT
TO_DATE('20240512') AS wrong1,
CAST('20240512' AS DATE) AS wrong2,
TO_DATE('20240512', 'YYYYDDMM') AS correct1,
CAST('20240512' AS DATE, 'YYYYDDMM') AS correct2;
In Postgres I can use TO_DATE
. CAST doesn't support format mask.
And what about SQL Server, when TO_DATE
doesn't exists and CAST
doesn't support format mask?
1条答案
按热度按时间gkl3eglg1#
To summarize the comment's as an answer:
YYYYMMDD
is a very specific format used to avoid localization issues. Same with the ISO8601 form,YYYY-MM-DD
. - panagiotis-kanavosin TSQL you can use
CAST
which is ANSI-SQL standard, or the more flexibleCONVERT
- CAST and CONVERT (Transact-SQL) . CONVERT accepts a style parameter when converting to a string:SELECT CONVERT(VARCHAR(8), GETDATE(), 112)
. It is worth pointing out that formatting a date does make it a string, as aDATE
does not have a format. – Patrick HurstLooks like OP needs
yyyyddmm
which is not an available style. So maybe useFORMAT
. – Charliefaceyou can't convert
12345678
to a date either. In the case you specify you're looking for the database to perform your ETL sanitation, which isn't really it's job. If you really want to convert 'YYYYDDMM' to aDATE
you should be parsing the input to be able to provide it in a standard order, but it is possible:SELECT '20233011', TRY_CAST('20230311' AS DATE), CAST(LEFT('20230311',4)+RIGHT('20230311',2)+SUBSTRING('20230311',5,2) AS DATE)
– Patrick HurstSql Server doesn't support format mask it does, using the
CONVERT
,PARSE
, orFORMAT
functions. The conversion you ask for though is essentially ..... evil. It will confuse every single developer and even yourself. By next month if not next Monday you won't remember you used a custom format instead of the standard one you see everywhere. You will convert 20240104 to April 1. – panagiotis-kanavos