在SQL开头添加0

时间:2011-12-20 23:53:17

标签: sql tsql

我有小桌子

Create Table TestDates
(
  TestDateId int identity (1,1),
  RunDateTime DateTime
)

我设法执行只带来时间的独特查询 如果小时或分钟小于10,我想加零

SELECT DISTINCT SUBSTRING(CONVERT(varchar, RunDateTime, 100), 13, 2) + ':'
+ SUBSTRING(CONVERT(varchar, RunDateTime, 100), 16, 2) + ' '
+ SUBSTRING(CONVERT(varchar, RunDateTime, 100), 18, 2) AS DistinctDate
from TestDates

参见示例

**Current Output     Desired Output**

8:1 PM               **08:01 PM** 
8:33 AM              **08:33 AM**

我尝试使用正确的功能,但它没有帮助

SELECT DISTINCT Right('00' + SUBSTRING(CONVERT(varchar, RunDateTime, 100), 13, 2),2) + ':'
+ Right('00' + SUBSTRING(CONVERT(varchar, RunDateTime, 100), 16, 2),2) + ' '
+ SUBSTRING(CONVERT(varchar, RunDateTime, 100), 18, 2) AS DistinctDate
from TestDates

请咨询

3 个答案:

答案 0 :(得分:1)

创建此函数并包装要应用它的任何日期时间字段。用法示例:

SELECT TestDateId,dbo.ProperHours(RunDateTime) FROM TestDates


CREATE FUNCTION dbo.ProperHours(
    @Time DATETIME
)
RETURNS CHAR(8)
AS
BEGIN
    DECLARE @Hours TINYINT
    DECLARE @Minutes TINYINT
    DECLARE @HoursAsString CHAR(2)
    DECLARE @MinutesAsString CHAR(2)
    DECLARE @AmPm CHAR(2)

    SELECT  @Hours=DATEPART(hh,@Time),
            @Minutes=DATEPART(n,@Time),
            @AmPm=CASE
                    WHEN DATEPART(hh,@Time)>=12 THEN 'PM'
                    ELSE 'AM'
                END

    IF @Hours>12
        BEGIN
            SET @Hours=@Hours-12
        END
    ELSE IF @Hours=0
        BEGIN
            SET @Hours=12
        END

    SELECT  @HoursAsString=CONVERT(VARCHAR,@Hours),
            @MinutesAsString=CONVERT(VARCHAR,@Minutes)

    IF LEN(@HoursAsString)=1
        BEGIN
            SET @HoursAsString = '0' + @HoursAsString
        END

    IF LEN(@MinutesAsString)=1
        BEGIN
            SET @MinutesAsString = '0' + @MinutesAsString
        END

    RETURN @HoursAsString + ':' + @MinutesAsString + ' ' + @AmPm
END
GO

答案 1 :(得分:1)

试试这个:

SELECT DISTINCT 
     Right('00'+LTRIM(SUBSTRING(CONVERT(varchar, RunDateTime, 100), 13, 2)),2) + 
     ':'
     + Right('00' + SUBSTRING(CONVERT(varchar, RunDateTime, 100), 16, 2),2) + ' '
     + SUBSTRING(CONVERT(varchar, RunDateTime, 100), 18, 2) AS DistinctDate
FROM TestDates

问题是第一个子字符串返回_8(空格8),因此您需要修剪该值以除去空格,然后添加00代码。

答案 2 :(得分:1)

SELECT Replace(SUBSTRING(CONVERT(varchar(100), RunDateTime,131), 12, 5), ' ', '0') 
  + ' ' 
  + SUBSTRING(CONVERT(varchar(100), RunDateTime,131), 24, 2)
from TestDates