user3306489
user3306489

Reputation: 157

Convert concatenated columns to date

How can I convert this piece of code into a date. I'm using a day column to create a date using the code below in TSQL.

convert(nvarchar(2),a.ucdaycode) + '/' +
    cast(month(GETDATE()) as varchar) + '/' +
    cast(YEAR(GETDATE()) as varchar)

Has anybody any any ideas?

Thanks

Upvotes: 0

Views: 38

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520918

Here is an option using DATEADD and DATEDIFF:

SELECT
    a.ucdaycode,
    DATEADD(dd, a.ucdaycode, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) AS some_date
FROM yourTable a;

enter image description here

Demo

The answer by @Zohar looks a bit cleaner than this, but it might only run on SQL Server 2012 or later.

Upvotes: 2

Zohar Peled
Zohar Peled

Reputation: 82474

Use DATEFROMPARTS:

SELECT DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), a.ucdaycode)

Upvotes: 1

Related Questions