T-SQL如何以hh:mm格式转换小时(int值)

时间:2017-07-13 10:00:06

标签: sql-server tsql

我想以这种格式hh:mm及时转换变量HOUR(INT)。 所以我有这个代码;

declare @HOUR_NEW AS INT = 12
DECLARE @RISULTATO AS NVARCHAR(12)
SET @RISULTATO = CONVERT(VARCHAR(12),@HOUR_NEW,108)
SELECT @RISULTATO

我想输出就像这个12:00但是选择返回12

4 个答案:

答案 0 :(得分:1)

以下代码包括带小时的分钟数和秒数

declare @HOUR AS INT = 1, @MIN AS INT = 1, @SEC AS INT = 2
DECLARE @RISULTATO AS time(3)
SET @RISULTATO = CONVERT(VARCHAR(2),@HOUR) + ':' +  CONVERT(VARCHAR(2),@MIN) + ':' + CONVERT(VARCHAR(2), @SEC) 
SELECT @RISULTATO

上面的代码使用的是数据类型时间。如果您只想以自己的方式进行操作,可以使用RIGHT,例如

declare @HOUR_NEW AS INT = 1
DECLARE @RISULTATO AS time(1)
SELECT RIGHT('00' + CONVERT(VARCHAR(2), @HOUR_NEW) ,2) + ':00'

答案 1 :(得分:0)

declare @HOUR_NEW AS INT = 12 
DECLARE @RISULTATO AS VARCHAR(12) 
SET @RISULTATO = CONVERT(VARCHAR(12),@HOUR_NEW) + ':00' SELECT @RISULTATO

答案 2 :(得分:0)

这可行:

if(condition)
{
    try2:

    // do stuff

    if(condition2)
    {
        // Do more stuff
    }
    else
    {
        // Report error
        goto try2;
    }

}

// Replace with:

while(condition)
{
    // do stuff

    if(condition2)
    {
        // Do more stuff
        break;
    }
    else
    {
        // Report error
        continue; // Goes to the top of the loop
    }
}

我只是将DECLARE @HOUR_NEW AS INT = 12 DECLARE @TIME TIME = '00:00:00'; SET @TIME = DATEADD(HOUR, @HOUR_NEW, @TIME); PRINT LEFT(@TIME, 5); 声明为当前时间,并使用00:00:00向其添加DATEADD()小时的数量。然后只打印它的前5个字符。

答案 3 :(得分:0)

以下解决方案应该适合您:

declare @result varchar(5) 
declare @hour int = 3
declare @hourString nvarchar(2) = (select cast(@hour as nvarchar))  

if (len(@hourString)<2)
    set @result =  '0' + @hourString + ':00' 
else
    set @result = @hourString + ':00' 

select @result