Como usar datediff para mostrar resultados como HH:MM:SS

/, SQL/Como usar datediff para mostrar resultados como HH:MM:SS

Como usar datediff para mostrar resultados como HH:MM:SS

A Veces necesitas HH:MM:ss

I ran into a case when I needed to display some results in the HH:MM:SS format. Todos conocemos DATEDIFF, que nos da resultados en números enteros. Usando DATEDIFF, miramos resultados como esto:

--	Declare dos variables de DATETIME
DECLARE	@START_DATE	DATETIME
DECLARE	@END_DATE	DATETIME	--	Actualice las variables a los valores deseados
SET		@START_DATE = '2011-01-01 16:00:00'
SET		@END_DATE =   '2011-01-01 22:47:22'
SELECT DATEDIFF(second,@Start_date, @END_DATE) AS Segundos
Segundos
24442
 
(1 row(s) affected)


Los resultados son correctos, pero no quiero entregar esto al usuario en este formato. Busqué y encontré lo que estaba buscando en SQLServerCentral.com. Aquí está la versión final en TSQL:

--	Declare dos variables de DATETIME
DECLARE	@START_DATE	DATETIME
DECLARE	@END_DATE	DATETIME	--	Actualice las variables a los valores deseados
SET		@START_DATE = '2011-01-01 16:00:00'
SET		@END_DATE =   '2011-01-01 22:47:22'--	Usa datediff para mostrar los resultados in HH:MM:SS
 
SELECT    CONVERT(varchar(6), DATEDIFF(second, @START_DATE, @END_DATE)/3600)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), (DATEDIFF(second, @START_DATE, @END_DATE) % 3600) / 60), 2)
+ ':'
+ RIGHT('0' + CONVERT(varchar(2), DATEDIFF(second, @START_DATE, @END_DATE) % 60), 2) AS 'HH:MM:SS'
HH:MM:SS
6:47:22

Los resultados vuelven en un formato más agradable y fácil de leer.

By | 2017-10-24T17:49:55-05:00 October 24th, 2017|Categories: 100, SQL|Tags: , , , |1 Comment

About the Author:

Mi nombre es Rodolfo y trabajo en Austin, Tejas. He estado trabajando con SQL Server desde 2003. Mi enfoque es SSRS, SSIS y el ajuste de rendimiento.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.

This Is A Custom Widget

This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.