简体   繁体   English

在 SQL Server 中将日期转换为 varchar

[英]Convert date to varchar in SQL Server

How do I convert a column which is date type to varchar ?如何将date类型的列转换为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 .如果我正确理解了这个问题,您需要将值'1947-12-01 00-00-00'ENDDATE作为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.如果您使用的是 2012 或更高版本,则可以使用 format。 For earlier versions you can use convert with some string manipulations:对于早期版本,您可以将 convert 与一些字符串操作一起使用:

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.请注意Format运行速度相对较慢,因此如果您有很多行,您可能需要选择另一种方式来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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