Formatting and comparing two dates fields - sql

I'm trying to compare two dates fields while i'm so formatting it but seems not to work. the select statement works but i'm having problem with the where clause
SELECT fname
,lname
,email
,rdate_up = CONVERT(VARCHAR(19), GETDATE())
,last_time = CONVERT(VARCHAR(19), GETDATE())
FROM my_account
WHERE my_account.email = MMColParam
AND rdate_up = CONVERT(VARCHAR(19), GETDATE()) < last_time_log = CONVERT(VARCHAR(19), GETDATE())

I'm guessing this isn't your real query as comparing GETDATE() to itself will always be equal.
If you want to convert dates in the SELECT that's fine, I'm guessing you meant this:
SELECT fname
,lname
,email
,CONVERT(VARCHAR(19), rdate_up)
,CONVERT(VARCHAR(19), last_time)
FROM my_account
But use the actual date values in your WHERE clause and get rid of the conversion:
WHERE my_account.email = MMColParam
AND rdate_up < last_time_log

Do not compare dates (or anything, for that matter,) after you have converted them to strings.
Compare them before converting to strings.
Convert something to a string only immediately prior to displaying it to a human being.
SELECT
date1,
date2 = GETDATE(),
date1toShowToAHumanBeing = CONVERT(VARCHAR(19), date1),
date2toShowToAHumanBeing = CONVERT(VARCHAR(19), date2)
FROM my_account
WHERE date1 < date2

Related

Putting a word in the select statement

I want to put the word "days" after the value, but the sql server is reacting that it cannot be converted. How can I also not select the negative integers difference.
SELECT PONo, PODeliveryDate, DATEDIFF(DAY, GETDATE(), PODeliveryDate) AS DayDiff
FROM PurchaseOrder
where POStatus='Complete' OR POStatus='Partially Completed' OR POStatus='Approved'
ORDER BY ABS( DATEDIFF( DAY, GETDATE(), PODeliveryDate ))
It gives me the difference of dates, but I cannot put the word days beside it.
I want it to look like 5 days not just 5
Try to convert the int value from DATEDIFF() to varchar and add your word
SELECT PONo
, PODeliveryDate
, CAST(DATEDIFF(DAY, GETDATE(), PODeliveryDate) as varchar(10)) + ' days' AS DayDiff
FROM PurchaseOrder
WHERE POStatus='Complete'
OR POStatus='Partially Completed'
OR POStatus='Approved'
ORDER BY ABS( DATEDIFF( DAY, GETDATE(), PODeliveryDate ))
Convert this first DATEDIFF(DAY, GETDATE(), PODeliveryDate) into VARCHAR before you concatinate.
CONVERT(VARCHAR(50), DATEDIFF(DAY, GETDATE(), PODeliveryDate)) + 'days'
In sqlserver 2012, you can use CONCAT.
To only get the positive days, you can cast getdate as date and compare with that in the WHERE statement. Then you dont need to order by ABS datediff.
The WHERE clause is easier to read and maintain by using IN instead of OR, it also makes is easier to maintain.
SELECT
CONCAT(DATEDIFF(DAY, GETDATE(), PODeliveryDate), ' days') AS DayDiff
FROM
PurchaseOrder
WHERE
POStatus in ('Complete','Partially Completed','Approved')
AND CAST(GETDATE() as date) <= PODeliveryDate
ORDER BY
PODeliveryDate
Can you try like as follow:
select CONVERT(varchar(10), GETDATE()) + ' Days'
You need to convert or cast into varchar before concate

Sort a varchar converted datetime column

I have a datetime column, dates are shown like "11/13/2012 1:48:27 PM" I need to convert it to "11/13/12".
I know I can convert it using
convert(varchar(10), datevalue, 1)
but when I sort the column after converting it's not sorting by date. I'm not sure if convert(datetime, datevalue, 1) is supposed to do anything but nothing happenend and I still got the default date value.
I tried this
select convert(varchar(10), datevalue, 1)
from table
order by convert(datetime, datevalue, 1) desc
It works but my bigger query selects distinct and I'm getting an error
ORDER BY items must appear in the select list if SELECT DISTINCT is specified
Try something like:
SELECT CONVERT(varchar(10), datevalue, 1)
FROM table
ORDER BY datevalue desc
Try this:
SELECT CONVERT(DATETIME, datevalue, 103)
FROM table
ORDER BY CONVERT(DATETIME, datevalue, 103)
select convert(varchar(10), datevalue, 1)
from table
order by datevalue desc
You don't need to convert date in order by statement. Only column name would work if its datatype is 'datetime'

converting date format to eliminate time stamp

I have a table where the date and time stamp are logged together and I want to only show the date in a 10 character output. Also I want to return as blank some dates in the field that are 01/01/1800.
The current table format is 2013-06-28 00:00:00:000
I just want the date. I was using RTRIM function but it keeps erroring out.
Thanking you in advance
Try this:
SELECT CASE CONVERT(DATE, #MyValue) WHEN '01/01/1800' THEN NULL ELSE CONVERT(DATE, #MyValue) END
Or if you prefer:
DECLARE #DateOnlyValue DATE
SET #DateOnlyValue = CONVERT(DATE, #MyValue)
SELECT CASE #DateOnlyValue WHEN '01/01/1800' THEN NULL ELSE #DateOnlyValue END
The latter is just DRYer.
You can just do:
select (case when datecol > '1800-01-01' then convert(varchar(10), datecol, 121) end)
This will convert the value to a string of the form YYYY-MM-DD.
This uses NULL for "blank". If you want an empty string:
select (case when datecol > '1800-01-01'
then convert(varchar(10), datecol, 121)
else ''
end)
This also assumes that the values with '1800-01-01' don't have a time component. That seems reasonable for a default extreme value.

Date Time conversion/ Date diff in SSRS

I have an SSRS report where I am using below query.
(This query works fine in SQL server, problem is only in SSRS report)
--DECLARE #Range Number = 10;
SELECT * FROM TBL1 WHERE
USERNAME = 'MIKE'
AND
(
#Range = '10'
and
Convert(datetime, MyDate, 120) <= GETDATE()
)
or
(
#Range IN ('20','30')
and
DATEDIFF(DD, Convert(datetime, MyDate, 120) , GETDATE()) <= #Range
)
Unfortunately the myDate Column coming from database is a varchar column.
The SSRS throws an out-of-range exception.
Then I tried converting Getdate to Convert(varchar(10), getdate(), 120) and compare with myDate (without conversion as myDate is already in YYYY-MM-DD format but as a varchar in database)it still throws error. I assume this time coz SSRS is not able to process datediff in varchar columns.
When I run these queries individually, it works fine. i.e -
Declare #Range Number = 10;
Select * from tbl1
where username = 'MIKE' and
(
#Range = '10'
and
convert(datetime, MyDate, 120) <= getdate()
Has anyone faced similar issue in SSRS ???
Try this!
SELECT * FROM TBL1 WHERE
USERNAME = 'MIKE'
AND
(
#Range = '10'
and
cast(myDate as datetime) <= GETDATE()
)
or
(
#Range IN ('20','30')
and
cast(myDate as datetime) , GETDATE()) <= #Range
)
Presumably, your problem is that some values of myDate are not in the correct format. If you are using a more recent version of SQL Server, the function try_convert() can be a big help.
The reason it is failing is because of your logic. The second condition after the or is looking at all records, not just Mike's. I think you intend for the where clause to be:
SELECT *
FROM TBL1 WHERE
WHERE USERNAME = 'MIKE' AND
((#Range = '10' and Convert(datetime, MyDate, 120) <= GETDATE()
) or
(#Range IN ('20','30') and
DATEDIFF(DD, Convert(datetime, MyDate, 120) , GETDATE()) <= #Range
)
);
Note the extra set of parentheses. Now, this will probably help for this particular query for MIKE. But it won't help overall. Finding the value(s) that fail conversion can be daunting. If you are lucky, they fail easily. You can look for them with starting with:
select MyDate
from tbl1
where MyDate not like '[0-9][0-9][0-9][0-9]-[0-2][0-9]-[0-3][0-9]%';
If you are lucky, then this will find the offending values. Otherwise, you'll have to dive more deeply into the date formats, looking at the particular month and day (and potentially hour, minute, and second) values.
Moral: Store dates as dates. Don't store them as varchar().

how to get before date Rates using sqlserver?

select rateperkg from K_FS_FeedMrpDetails where date = getdate()-1
I want to display rateperkg column before date values
Try this
get Yesterday
select rateperkg from K_FS_FeedMrpDetails where date = DATEADD(d,-1,GETDATE())
see this link for more details.
I think this will helps you
http://blog.sqlauthority.com/2008/08/29/sql-server-few-useful-datetime-functions-to-find-specific-dates/
This code will set time to zero.
declare #DaVal as datetime
--111 will return yyyy/MM/dd
--101 will return MM//dd/yyyy
set #DaVal = convert(datetime, convert(varchar(25), DATEADD(d,-1,GETDATE()), 111))
select rateperkg from K_FS_FeedMrpDetails where date = #DaVal
Try using DATEADD() function and cast it to Date to remove time part like below
SELECT rateperkg
FROM k_fs_feedmrpdetails
WHERE date = Cast(Dateadd(day, -1, Getdate()) AS DATE);
If your date column stores date and time then use the below condition
where date >=convert(date,getdate()-1)
and date < getdate()
else
where date = convert(date,getdate()-1)