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
  • 34,946
  • 5
  • 87
  • 124
Behnam
  • 1,039
  • 2
  • 14
  • 39

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,696
  • 1
  • 14
  • 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,242,037
  • 58
  • 646
  • 786
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,477
  • 5
  • 26
  • 36
0
SELECT CONCAT(day, '/', month, '/', year) AS Date
Matt
  • 14,906
  • 27
  • 99
  • 149
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,600
  • 5
  • 33
  • 59
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,600
  • 5
  • 33
  • 59
Recursive
  • 954
  • 7
  • 12