0

我有 3 个 varchar 时间范围,它应该被转换为开始和结束时间值,

这是价值:

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)

如何仅将一个值转换为时间值,或者是否有任何简单的转换?

4

1 回答 1

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
于 2013-10-25T03:43:30.910 回答