Create a date from day month and year with T-SQL
Creating a date using DATEFROMPARTS(year, month, day)
in T-SQL is as easy as:
However, if you're dealing with an older version of SQL server that doesn't support DATEFROMPARTS
, you can use string concatenation and casting:
Each of these methods offers a simple and effective way to build a date.
Crafting dates: DATEFROMPARTS
in SQL Server 2012+
In SQL Server 2012 and onward, we use DATEFROMPARTS
for date creation. It allows us to use either column values or variables:
This function has the bonus feature of checking any invalid dates you try to create, shouting "You shall not pass!" to them.
Date crafting in older SQL Server versions
Absent DATEFROMPARTS
, in SQL Server 2005, nested DATEADD functions
incrementally build the date, beginning with the base date (1900-01-01):
Optimal date creation: avoid string casting
Rev up your SQL Server performance by not casting or converting from strings. SQL Server stores dates as day counts dating from 1900-01-01; leveraging this enables efficient integer arithmetic on dates.
Initiate adjustments with years to accurately register leap years; then proceed to adjust months and days.
Alternate date crafting techniques in T-SQL
Arithmetic assembly - a precise sequence matters
Ensure order of additions is followed—add years as months, then actual months, finally days. Like a good symphony, there's a sequence that pleases SQL Server!
String concatenation and casting
Though less efficient, combining date variables into a string then casting might be required in some cases:
Don't ignore zero-padding for single-digit months and days to maintain Y-M-D formatting!
Common pitfalls and how to avoid them
Validating input
Check your date components with the eye of a detective, ensuring validity and data types of inputs. Enlist TRY_CONVERT
or TRY_CAST
for proactive error detection:
Zero-padding for single-digit months and days
Zero-pad single-digit months and days to keep your date strings in Y-M-D format:
This ensures correct string format for any date construction.
Was this article helpful?