如何让sqlserver只返回年和月

如何让sqlserver只返回年和月

select convert(varchar(7),date_colName,121) from table通过convert来对日期进行格式化,只返回年月部分。CONVERT() 函数可以用不同的格式显示日期/时间数据。基本语法如下:

CONVERT(data_type(length),data_to_be_converted,style)data_type(length) 规定目标数据类型(带有可选的长度)。

data_to_be_converted 含有需要转换的值。style 规定日期/时间的输出格式。

如上121的格式对应为:yyyy-mm-dd hh:mi:(24h)而上面定义的varchar(7),因此返回7个长度,即yyyy-mm