Question

in database table I got :

int day
int month
int year

I want to write a select query to show the date : dd/mm/yyyy

I try this but didn't work :

1-

select (day + '\' + month + '\' + year) as xdate from table1

but give me an error

2-

select (day + '-' + month + '-' + year) as xdate from table1

it return the sum of these field : 2036 instead of 21/1/2014

any solution ?

Was it helpful?

Solution

Try something like this:

select (cast(day as varchar(2)) + '/' 
    + cast(month as varchar(2)) + '/' 
    + cast(year as varchar(4))) as xdate 
from table1

OTHER TIPS

If TSQL / SQL-SERVER, then + only works to concatenate strings... So do some conversions on your numbers in that case:

select
   CONVERT(VARCHAR, day) + '\' + CONVERT(VARCHAR, month) + '\' ... etc.

Since you are Casting int to Varchar, so you need to use CAST or CONVERT function

CAST and CONVERT

Try like this

select (Cast(day AS Varchar(10)) + '\' + Cast(month AS Varchar(10)) + '\' + Cast(year AS Varchar(10))) as xdate from table1

(Or)

select (Cast(day AS Varchar(10)) + '-' + Cast(month AS Varchar(10)) + '-' + Cast(year AS Varchar(10))) as xdate from table1

CONVERT(date, , 103) converts a date to a string representation in dd/mm/yyyy form

SELECT CONVERT(date,DATEFROMPARTS([year],[month],[day]),103)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top