简体   繁体   中英

Convert date to varchar in SQL Server

How do I convert a column which is date type to varchar ?

Sample data:

ENDDATE (DATE TYPE)
'1947-12-01 00-00-00' 

Requested results:

ENDDATE (VARCHAR)
    121947

If I understand the question correctly, you need the ENDDATE of value '1947-12-01 00-00-00' as 121947 . You can use the below query

SELECT RIGHT(MONTH(ENDDATE)*1010000+YEAR(ENDDATE),6)

If you are working with 2012 version or higher, you can use format. For earlier versions you can use convert with some string manipulations:

DECLARE @D as date = '1947-12-01'

SELECT  REPLACE(RIGHT(CONVERT(char(10), @d, 103), 7), '/', '') As charValue2008,
        FORMAT(@d, 'MMyyyy') as charValue2012

Results:

charValue2008   charValue2012
121947          121947

Please note that Format runs relativley slow, so if you have a lot of rows you might want to choose another way to do that.

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