Datefromparts and datepart puzzle

145 Views Asked by At

Can someone tell what I'm doing wrong in SQL Server to fail to make the below on today (which is 2023-03-16) not read 3-20-2023?

Basically I need to return today's date only the day always has to be 20.

DECLARE @year int = CONVERT(int,datepart(yyyy, GETDATE()))
DECLARE @month int = CONVERT(int,datepart(m, GETDATE()))
DECLARE @day int = 20

SELECT DATEFROMPARTS(@month, @day, @year)
3

There are 3 best solutions below

2
Brian Campbell On

this works:

declare @month varchar(2) = month(getdate())
declare @year varchar(4) = year(getdate())
declare @day varchar(2) = '20' select @year + '-' + @month  + '-' + @day
0
Quinn Williams On

DATEFROMPARTS needs to be in year,moth,day format to work. Once you fix that you can convert it to any style you need.

 DECLARE @year int = CONVERT(int,datepart(yyyy, getdate()))
 DECLARE @month int = CONVERT(int,datepart(m, getdate()))
 DECLARE @day int = 20

     SELECT CONVERT(varchar, (datefromparts(@year, @month, @day )),10)
0
Martin Smith On

Basically I need to return today's date only the day always has to be 20.

You can use the below for this (get last day of previous month and add 20 days to it)

SELECT DATEADD(DAY,20,EOMONTH(GETDATE(), -1))

Or if you are on SQL Server 2022 you may prefer

SELECT DATEADD(DAY,19,DATETRUNC ( MONTH , GETDATE()))