Home >Database >Mysql Tutorial >SQL中用格式字符串定制日期转字符串

SQL中用格式字符串定制日期转字符串

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 15:04:371060browse

在C#中用惯了DateTime.ToString("yyyy-MM-dd"),DateTime.ToString("MM/dd/yyyy")这种日期与字符串的转换方式,在SQL server中没得用,于是乎写了个FUNCTION,功能跟.net 中的DateTime.ToString("formatprovide")方法差不多,不过只实现了日期部分,有兴趣的


在C#中用惯了DateTime.ToString("yyyy-MM-dd"),DateTime.ToString("MM/dd/yyyy")这种日期与字符串的转换方式,在SQL server中没得用,于是乎写了个FUNCTION,功能跟.net 中的DateTime.ToString("formatprovide")方法差不多,不过只实现了日期部分,有兴趣的朋友可以把时间部分补充出来。

create function fn_DateToString(@date datetime, @format varchar(20))

returns varchar(20)

as

begin

declare @result varchar(20)

select @result = (replace(replace(replace(@format,'yyyy','20'+substring(convert(char(8),@date,3),7,2)),'MM',substring(convert(char(8),@date,3),4,2)),'dd',substring(convert(char(8),@date,3),1,2)))

return @result

end

使用:

select dbo.fn_datetostring(getdate(),'yyyy-MM-dd')

得到结果:2005-07-12

本文作者:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn