0

Consider three parameters:

@Y=2014
@M=11
@D=24

I want to have a function in SQL Server which gets three numbers and return one date as result.

Jodrell
  • 32,967
  • 4
  • 79
  • 120
Behnam
  • 874
  • 1
  • 14
  • 33

7 Answers7

6

You can use SQL Server 2012 DATEFROMPARTS function.

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

For versions below 2012, I'd use:

SELECT CONVERT(DATETIME, STR(@year * 10000 + @month * 100 + @day))
CrimsonKing
  • 2,416
  • 12
  • 11
1

You could do:

select cast(cast( (@y * 10000 + @m * 100 + @d) as varchar(255)) as date)

But datefromparts() is best if you are using SQL Server 2012+.

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0
create function dbo.formatDate(@Y int, @M int, @D int)
returns date
as
begin
    declare @retDate date
    select @retDate =  cast(cast(@Y as varchar) + '-' + cast(@M as varchar) + '-' + cast(@D as varchar) as date)
    return @retDate
end

Testing:

select dbo.formatDate(2014, 11, 24)
Eduard Uta
  • 2,382
  • 3
  • 27
  • 35
0
SELECT CONCAT(day, '/', month, '/', year) AS Date
Matt
  • 14,007
  • 25
  • 88
  • 136
0

this is a duplicate of this question

https://stackoverflow.com/a/1923918/3632420

SELECT
   CAST(
      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
   AS DATETIME)
Community
  • 1
  • 1
sdhd
  • 123
  • 2
  • 10
0

If you are using SQL Server 2000 and above use the below query

Select MyDate=cast(DateAdd(day, @DayOfMonth - 1, 
          DateAdd(month, @Month - 1, 
              DateAdd(Year, @Year-1900, 0))) as date) 

If you are using SQL Server 2012 and above use the built function DATEFROMPARTS like

select DATEFROMPARTS(@year, @month, @day)
Rajesh
  • 1,546
  • 5
  • 31
  • 54
0

Try this,

declare  @Y int=2014
declare  @M  int =11 
declare  @D int =2

SELECT CONVERT(VARCHAR(12), (SELECT Cast(@d AS VARCHAR(20)) + '-'
                                    + Cast(@M AS VARCHAR(20)) + '-'
                                    + Cast(@y AS VARCHAR(20))), 110) 

Change the 110 accordingly needed for different formats

formats in sql server datetime conversion

Rajesh
  • 1,546
  • 5
  • 31
  • 54
Recursive
  • 944
  • 7
  • 12