Conversion of Date from Varchar in SQL Server


Hello & Welcome All,

Here I am going to explain you one of the very important thing i.e. conversion of Date from varchar. I have seen so many times we face the problem while converting the date from varchar.

Here is one live example we are passing two parameter as Year and Month and we need to convert it into the date as Considering the first day of the month in date.

Here is how we can do it.


DECLARE @Year AS INT
DECLARE @Month AS INT

SET @Year=2012
SET @Month=4

DECLARE @varFromDate AS VARCHAR(25)
DECLARE @fromDate AS DATETIME
SET @varFromDate = ''+CAST(@Month AS VARCHAR)+''+'-'+'01'+'-'+CAST(@Year AS VARCHAR)
SET @fromDate=CAST(@varFromDate AS DATETIME)
PRINT @fromDate
PRINT DATENAME(MM,@fromDate)  --Here you will get the month name
Feel free to know me in case of any query.

Cheers,
Ved Pathak


Comments