I want to truncate a datetime(7)
at different lengths - determined by parts - in SQL Server 2019 (DATETRUNC
starts on 2022 *). Kind of "year-month", "year-month-day", ... up to seconds.
In case below I truncate up to minute (leaving seconds a precision):
SELECT
FORMAT(DATEPART(year,my_col), '0000')
+ '-' + FORMAT(DATEPART(month,my_col), '00')
+ '-' + FORMAT(DATEPART(day,my_col), '00')
+ ' ' + FORMAT(DATEPART(hour,my_col), '00')
+ ':' + FORMAT(DATEPART(minute,my_col), '00') AS my_col
FROM my_schema.my_table
I get "2025-06-10 19:43" - which is OK.
Any shorter code that would do the work of DATETRUNC
? And that (at best) would return a type of date and not string?
If your parts
is a column with a format()
-compatible string, you can directly use it to go to then back from string (convert
for the "from" part):
select *, convert(datetime, format(my_col, parts), 120) truncated
from my_table;
parts | my_col | truncated |
---|---|---|
yyyy-MM-dd HH:mm:ss | 2025-06-15 22:34:30.800 | 2025-06-15 22:34:30.000 |
yyyy-MM-dd HH:00:00 | 2025-06-15 22:34:30.800 | 2025-06-15 22:00:00.000 |
yyyy-MM-01 00:00:00 | 2025-06-15 22:34:30.800 | 2025-06-01 00:00:00.000 |
(see it in a fiddle to test on)
Of course this requires that you have total control over parts
, so that its format is not broken by user input!
If this is not the case, you'll rely on a mapping from each of your parts
value to the corresponding format.