SQL Server Create a date column from the month and year and a static day

6kkfgxo0  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(122)

I have 'Year' and 'Month' columns in my SQL table. No column for Day. Example below.
| Year | Month |
| ------------ | ------------ |
| 2010 | 10 |
| 2008 | 8 |
| 2021 | 11 |
| Null | Null |
| 2009 | 2 |

I would like to create a 'Date' column (YYYY-MM-DD) where YYYY='Year', MM='Month', and DD=15. So, the values of the newly created 'Date' column will be as shown below:

Date
2010-10-15
2008-8-15
2021-11-15
Null
2009-2-15

I tried the following code

CONCAT(Year,'-',Month,'-',15) as Date

and got as below

Date
2010-10-15
2008-8-15
2021-11-15
--15
2009-2-15

I would like to get Null for the 'Date' where either year, or month, or both are Null . I also would like to use the newly created values in the 'Date' column as a date.

Please help

6ovsh4lw

6ovsh4lw1#

As I said in the comments of your original question, use CASE to detect the NULL situation, and if not NULL use DATEFROMPARTS e.g.

case when [Year] is not null and [Month] is not null
then datefromparts([Year], [Month], 15)
else null
end

相关问题