Saturday, May 12, 2012

Split a String Using Delimiter

Split a String Using Delimiter


Create Function [dbo].[f_StringSplit]

(  

    @DelimitedList nvarchar(max)

    , @Delimiter nvarchar(2) = ','

)

RETURNS TABLE

AS

RETURN

    (

    With CorrectedList As

        (

        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End

            + @DelimitedList

            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End

            As List

            , Len(@Delimiter) As DelimiterLen

        )

        , Numbers As

        (

        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value

        From sys.columns As c1

            Cross Join sys.columns As c2

        )

    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Strat_Position

        , Substring (

                    CL.List

                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen    

                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                          

                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )

                    ) As Value

    From CorrectedList As CL

        Cross Join Numbers As N

    Where N.Value <= DataLength(CL.List) / 2

        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter

    )

OUTPUT

select * from [dbo].[f_StringSplit] ('Career Opportunities,Cross – Functional & Business Exposure,Designation,Infrastructure: Transportation/ Cafeteria etc.,',',')

Strat_Position

Value

2

Career Opportunities

23

Cross – Functional & Business Exposure

62

Designation

74

Infrastructure: Transportation/ Cafeteria etc.



Thursday, May 10, 2012

HOUR MINITE CALCULATION(find a difference between two different DATE)

HOUR MINITE CALCULATION(find a difference between two different DATE)

 

select

CAST(case when left(Minutes_Difference,1)='-' then Hours_Difference-1 else Hours_Difference end as varchar(10) )+':'+

cast(case when left(Minutes_Difference,1)='-' then 60+Minutes_Difference else Minutes_Difference end as varchar(10)) [Duration] from

(

 select DATEDIFF(HOUR,'2012-05-01 10:06:11.163','2012-05-03 13:03:15.840') as                                  Hours_Difference

,DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh,'2012-05-01 10:06:11.163', '2012-05-03 13:03:15.840'),'2012-05-01 10:06:11.163'),'2012-05-03 13:03:15.840') as    Minutes_Difference

) t