Tạo một hàm với định dạng trả về yyyy-mm-hh hh: mi: ss.sss
create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare
@w_fecha varchar(23),
@w_anio varchar(4),
@w_mes varchar(2),
@w_dia varchar(2),
@w_hh varchar(2),
@w_nn varchar(2),
@w_ss varchar(2),
@w_sss varchar(3)
select @w_fecha = null
if ltrim(rtrim(@i_fecha)) is not null
begin
select
@w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
@w_mes = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
@w_dia = replicate('0',2-char_length( convert(varchar(2), day(@i_fecha)) )) + convert(varchar(2), day(@i_fecha)) ,
@w_hh = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
@w_nn = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
@w_ss = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
@w_sss = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) ) ))
select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end
return @w_fecha
end
go
Thí dụ
select fn_retornaFecha(getdate())
và kết quả là: 2016-12-21 10: 12: 50.123