convert varchar to date sqlserver
convert varchar to date sqlserver
I have a day in varchar
and month and year also in varchar
they are separated how to convert it in date
format in SQL server
varchar
varchar
date
We can't see your data. Please provide some samples. This sounds like, however, you've made the mistake of storing your data as the wrong data type, and (unsurprisingly) its come to back to bite you. Alwats use the correct data type for your data. stores dates as a
date
, times as a time
, date && times and datetime2
, numerics as a int
/decimal
, etc, etc. varchar
is not a "one size fits all` datatype. sql_variant
almost fulfils that, but still, you should be using the proper data type when you can.– Larnu
Jul 3 at 9:38
date
time
datetime2
int
decimal
varchar
sql_variant
Concatenate and convert
– apomene
Jul 3 at 9:38
You can also use
DATEFROMPARTS()
.– HoneyBadger
Jul 3 at 9:39
DATEFROMPARTS()
2 Answers
2
DECLARE @Year nvarchar(50) = '2018'
DECLARE @Month nvarchar(50) = '7'
DECLARE @Day nvarchar(50) = '3'
SELECT DATEFROMPARTS(@Year, @Month, @Day)
use CONVERT() or CAST() to convert
SELECT CONVERT(DATETIME, year_column + month_column + '01') as DateTimeColumn
i use cast mais but is display an error
– malak laghoz
Jul 3 at 10:04
select cast(cast(p.Year*10000 + p.Month*100 + p.Day as varchar(255)) as date) FROM Personnel p SELECT CAST(CONCAT(CAST(p.Year AS VARCHAR(4)), '-',CAST( p.Month AS VARCHAR(2)), '-',CAST(p.Day AS VARCHAR(2))) AS DATE) FROM Personnel p SELECT convert(date, CONVERT(nvarchar(10), Year) + '-' + CONVERT(nvarchar(10), Month) + '-' + CONVERT(nvarchar(10), Day)) as 'Date' FROM Personnel;
– malak laghoz
Jul 3 at 10:05
@malaklaghoz please update your original question with the query
– Squirrel
Jul 3 at 13:54
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
show some sample input data
– Chanukya
Jul 3 at 9:38