Question

I Have 3 varchar Time Range and it should be Converted to start & Finish time value,

here's the value :

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

so I tried by myself to split into start time and finish and convert to time value

here's my split Function :

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

and I get the start & Finish value by do this in my dev query , but when i tried to convert 15-17:30 , I Got an error Conversion, because the start value is only 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)

how to convert only one value as Time value, or is there any simple conversion?

Was it helpful?

Solution

I Already Fix my Split Function, so if the start time have no Minutes value so it's add automatically

here's my code

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top