Difference between two dates [Resolved]

Posted by Charan44 under Sql Server on 1/1/2017 | Points: 10 | Views : 586 | Status : [Member] | Replies : 5
Hello Sir,
I Have to get the data by difference between two dates in sql server 2008
1.as Data type is CreatedBy Varchar(50)
2.as data type is OrderedOn Datetime

they are two different tables when i want to get data from first type but the data type is varchar

Please can you suggest how to get data for both data types




Responses

Posted by: Bandi on: 1/3/2017 [Member] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
SELECT * FROM TableName
WHERE YEAR(convert(datetime, OrderedOn)) BETWEEN 2015 AND 2016


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Charan44, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheonarayan on: 1/2/2017 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Hi Charan44,

You will need to first convert the varchar(50) date time to DateTime type in Sql Server.

DECLARE @createdBy DateTime

SET @createdBy = convert(datetime, CreatedBy)


To get the Date difference, use DateDiff function explained at http://techfunda.com/howto/172/get-difference-between-two-dates.

Hope this will help.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Charan44, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 1/2/2017 [Member] [MVP] Silver | Points: 25

Up
0
Down
Try the below code:

DECLARE @CreatedBy DateTime
Set @CreatedBy = CONVERT(Datetime, CreatedBy, 120)
SELECT DATEDIFF(day, @CreatedBy , OrderedOn) AS DiffDate


Charan44, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Charan44 on: 1/3/2017 [Member] Starter | Points: 25

Up
0
Down
Dear Sir,
i have table like this
 User  varchar(50),

ItemName Varchar(50),
OrderedOn varchar(50)
// this is date
now i want the query to display data based on users orders from 2015 to 2016

Charan44, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: A2H on: 1/3/2017 [Member] [MVP] Silver | Points: 25

Up
0
Down
An Alternative option is to use DATEPART function like below
SELECT * FROM TableName
WHERE DATEPART(Year,CAST(OrderedOn AS datetime)) BETWEEN 2015 AND 2016


Thanks,
A2H
My Blog

Charan44, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response