将Varchar转换为时间范围

时间:2013-10-25 03:07:05

标签: sql time split varchar

我有3个varchar时间范围,它应该被转换为start&完成时间值,

这是值:

SCH
 - 9:00-12:00 
 - 13-15:00 
 - 15-17:30

所以我自己尝试分成开始时间和结束并转换为时间值

这是我的分割功能:

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

我得到了开始&通过在我的开发查询中执行此操作来完成值,但是当我尝试转换15-17:30时,我得到了错误转换,因为起始值仅为15:

 declare @valueToParse varchar(20) = '15-17:30'

    select @schtimestart = data  from dbo.split(@valueToParse,'-') where id=1
    select @schtimefinish = data from dbo.split(@valueToParse,'-') where id=2
    SELECT CAST(@schtimestart AS time)
    SELECT CAST(@schtimefinish AS time)

如何只将一个值转换为时间值,还是有任何简单的转换?

1 个答案:

答案 0 :(得分:0)

我已经修复了我的分割功能,所以如果开始时间没有分钟值,那么它会自动添加

这是我的代码

USE [Dispatch]
GO
/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 25/10/2013 09:39:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

alter FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1
    declare @tmp as varchar(20)
    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        SET @tmp = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
        Insert Into @RtnValue (data)
        Select Data = case when ISNUMERIC(SUBSTRING(@tmp,1,2)) = 1 AND  ISNUMERIC(SUBSTRING(@tmp,4,2)) = 1 then   @tmp else  (@tmp + ':00') END

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END