Get only time or only Date from a datetime string in SQL

If you have a datetime in string format or as varchar, than you can cast this string or varchar in datetime format.

And if you want to retrieve only date or only time from datetime than query is below.

CAST() method, you can use for conversation from any format to any other format in SQL


CAST(’01/14/2019′ AS DATETIME)

CAST(’01/14/2019′ AS TIME)

CAST(’01/14/2019′ AS DATE)

How to split string in sql through sql function?

You can create a function for split the string.

you have to declare 2 parameters, first string that you want to split and second delimiter.

Here the function below :

CREATE FUNCTION [dbo].[fnSplitString] 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1
        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)