简体   繁体   中英

Temporarily change format of a date column in SQL Query output MM/YY -> MM/DD/YYYY

I have data on my SQL Server that is formatted like so:

06/21 

MM/YY

I would like to manipulate it so that all the dates are displayed as MM/DD/YYYY. So as the previous example it would look like:

06/01/2021

I was wondering if there is some sort of function that I can run in my query to display the date column differently in my output? I don't want to actually alter the way in which the Column is formatted on the back end, I just want to change how it is presented to the user in the results of a single query.

Thank you for your help!

Using STUFF

declare @var varchar(64) = '06/21 '
select stuff(@var,4,0,'01/20')

So for your table.

select stuff(yourColumn,4,0,'01/20')
From yourTable

Just replace / with 01/20 :

declare @yourDate varchar(10) = '06/21'
select replace(@yourDate ,'/','/01/20')

Result:

在此处输入图片说明

But it is probably wiser to cast it to a proper date type:

declare @yourDate varchar(10) = '06/21'
select cast(replace(@yourDate ,'/','/01/20') as date)

you can use this solution it works with all years 1998, .. 2000,2001 ...

declare @theDate varchar(10) = '06/21'
select convert(date,'01/'+ @theDate ,3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM