SQL里面两个日期相减

来源:百度知道 编辑:UC知道 时间:2024/07/08 00:17:27
2008-8-4 9:36:41 减去 2008-8-2 9:33:39
要求结果格式:
x天x小时x分钟x秒

DECLARE @dt1 AS datetime, @dt2 AS datetime;
SELECT @dt1 = '2008-8-4 9:36:41', @dt2 = '2008-8-2 9:33:39';

DECLARE @Days AS int, @Hours AS int, @Minutes AS int, @Seconds AS int;

SET @Seconds = DATEDIFF( second, @dt2, @dt1);
SET @Days = @Seconds / (24 * 60 * 60)
SET @Seconds = @Seconds - @Days * 24 * 60 * 60
SET @Hours = @Seconds / (60 * 60);
SET @Seconds = @Seconds - @Hours * 60 * 60
SET @Minutes = @Seconds / 60;
SET @Seconds = @Seconds - @Minutes * 60;
SELECT CONVERT(varchar(10), @Days ) + '天' + CONVERT(varchar(10), @Hours ) + '小时' + CONVERT(varchar(10), @Minutes ) + '分' + CONVERT(varchar(10), @Seconds ) + '秒';