Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the suggested date format to use in SQL Server?

I’ve seen a few variations of writing dates in SQL Server as it doesn’t support the more standard literal format of:

DATE '2014-01-01'

Is there a suggested way to write date-literals (or the closest thing to it) in SQL Server? Currently what I do is:

CAST('2014-01-01' AS date)

Whenever I want to use a date. Is this the most common?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

SQL Server supports some date formats, but you can use ‘20220101’

CREATE TABLE t1([date]  date)
INSERT INTO t1 values ('20220101')
SELECT * FROM t1
| date       |
| :--------- |
| 2022-01-01 |

db<>fiddle here

You are missunderstanding sql for TSQL

In your SELECT date, '20220101' FROM t1the second is a string for sql

But as you see in the query below, TSQL will convert the text i8no a date automatically when comparing for example

SELECT CASE WHEN CAST('2014-01-01' AS date) > '20220101' THEN 'TRUE' ELSe 'FaLSE' END 
| (No column name) |
| :--------------- |
| FaLSE            |

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading