如何使用其中一个T-SQL文本函数来获取字符串的一部分

时间:2010-10-13 23:30:59

标签: sql sql-server sql-server-2005 tsql

我有以下代码段:

 CONVERT(varchar, FLOOR(ROUND((DATEDIFF(minute, shiftStart.timeEntered, shiftEnd.timeEntered) - DATEDIFF(minute, 
                      lunchStart.timeEntered, lunchEnd.timeEntered)) * 1.0 / 60, 2, 1))) + ':' + CONVERT(varchar, ROUND(ROUND(DATEDIFF(minute, shiftStart.timeEntered, 
                      shiftEnd.timeEntered) * 1.0 / 60, 2, 1) % 1 * 60, 0)) AS WorkingHours

以上代码按以下格式打印小时和分钟:

4:30.000000
7:40.000000
8:1.000000

我需要摆脱。和下一个0,所以我得到以下格式:

4:30 (4 hours and 30 mins)
7:40 (7 hours and 40 minutes)
8:1 (means 8 hours and 1 minute)

.0000不伤害但是看起来很糟糕

1 个答案:

答案 0 :(得分:1)

在转换为VARCHAR之前将分钟部分转换为INTeger以删除小数值:

CONVERT(VARCHAR, 
        CONVERT(INT, ROUND(ROUND(DATEDIFF(minute, shiftStart.timeEntered, shiftEnd.timeEntered) * 1.0 / 60, 2, 1) % 1 * 60, 0))) 

完整示例:

CONVERT(varchar, FLOOR(ROUND((DATEDIFF(minute, shiftStart.timeEntered, shiftEnd.timeEntered) - DATEDIFF(minute, lunchStart.timeEntered, lunchEnd.timeEntered)) * 1.0 / 60, 2, 1))) + ':' + 
CONVERT(VARCHAR, CONVERT(INT, ROUND(ROUND(DATEDIFF(minute, shiftStart.timeEntered, shiftEnd.timeEntered) * 1.0 / 60, 2, 1) % 1 * 60, 0))) AS WorkingHours