SQL 在sql中使用datepart()得到一个两位数怎么办?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13758631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:29:34  来源:igfitidea点击:

what to do get a two digit number by using datepart () in sql?

sqlsql-server

提问by user1751909

I am trying to use DatePartto return a two digit hour. I would like to see 01, 02, 03, ...10, 11, 12for the hours. How can I do this?

我正在尝试使用DatePart返回两位数的小时。我想看01, 02, 03, ...10, 11, 12几个小时。我怎样才能做到这一点?

if I entered query as,

如果我输入查询,

select DATEPART(hour,'1900-01-01 07:45:00.010')

then I am getting answer 7. I need to get answer as 07.

然后我得到答案7。我需要得到答案为07.

回答by Sachin Shanbhag

Try this for MySql or from SQL Server 2012-

为 MySql 或SQL Server 2012尝试此操作-

select FORMAT(DATEPART(hour,'1900-01-01 07:45:00.010'),'00')

For SQL Server before 2012 -

对于 2012 年之前的 SQL Server -

select right('0' + DATEPART(hour,'1900-01-01 07:45:00.010'),2)

回答by Jeff Mergler

I couldn't get the above* solutions to work against SQL Server 2008.

我无法使用上述* 解决方案来对抗 SQL Server 2008。

What worked for me was:

对我有用的是:

select right('0' + convert(varchar,DATEPART(hour,'1900-01-01 07:45:00.010')),2)

returns

回报

07

*all the SQL Server solutions above returned "7" for me, not "07". Instead I used the convert(varchar...to make the "0" + "07" a concatenation of string to string, not string to numeric.

*上面的所有 SQL Server 解决方案都为我返回了“7”,而不是“07”。相反,我使用convert(varchar...使“0”+“07”成为字符串到字符串的连接,而不是字符串到数字的连接。

回答by Devart

Try FORMATfunction (supported in Sql Server 2012) -

尝试FORMAT函数(在 Sql Server 2012 中支持)-

DECLARE @d DATETIME = '1900-01-01 07:45:00.010';
SELECT FORMAT(@d, 'hh' )
>07

回答by Sergey

In MS SQL

在 MS SQL 中

select right('0' + DATEPART(hour,'1900-01-01 07:45:00.010'),2)

This is works

这是作品

回答by Amadan

In MySQL,

在 MySQL 中,

SELECT LPAD(thing_to_pad, 2, '0')

In MS SQL (I think - I don't use it):

在 MS SQL 中(我认为 - 我不使用它):

SELECT RIGHT('0' + thing_to_pad, 2)

回答by Savas Adar

you can do like this for mssql;

你可以对 mssql 这样做;

 RIGHT('0' + RTRIM(DATEPART(dd, date)), 2)