SQL Date as INT to Date for Query - sql-server-2012

I have a query built on the msdb..sysjobhistory table the MSDB database of my SQL Server. I want to be able to only give me back the stuff with the previous date. (in this example, 1/14/2015 would be yesterday) How do I go about this when the run_date information is in YYYYMMDD Integer format?
SELECT server
, jh.run_date
, jh.run_time
, j.name
, jh.run_duration
, jh.step_name
, run_status
, message
FROM msdb..sysjobhistory jh
INNER JOIN msdb..sysjobs j ON jh.job_id = j.job_id
WHERE jh.step_id = 0
Please advise.
-Nick

You could try converting that INT first to a VARCHAR and then using the 112 "Style" (noted on the MSDN page for Cast and Convert), convert that to a real DATETIME. For example:
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), 20150115), 112)
Of course, doing that alone would invalidate an index on the [run_date] field, if there is one. If that is the case, then you can just do the DATEADD to substract a day and then convert back to VARCHAR and then to INT. For example:
SELECT CONVERT(INT,
CONVERT(VARCHAR(10),
DATEADD(DAY,
-1,
CONVERT(DATETIME, CONVERT(VARCHAR(10), 20150115), 112)
),
112
)
);
On my SQL Server 2012 instance there is no index on [run_date], but might be best to still not wrap a field around a function.
If just using a DATETIME value, such as provided by GETDATE(), it would look like:
WHERE jh.step_id = 0
AND jh.run_date = CONVERT(INT,
CONVERT(VARCHAR(10),
DATEADD(DAY, -1, GETDATE()),
112)
)

Related

How can I convert datatime to int data type with GETDATE() function?

I have two problems.
How can I get today's date without time?
How can I convert datetime type into int type?
Just use the following queries:
Q1:How can I get Today's date without time ?
SELECT CONVERT(DATE, GETDATE());
Q2:How can I convert datetime type into int type ?
SELECT YEAR(GETDATE()) * 10000 + MONTH(GETDATE()) * 100 + DAY(GETDATE())
Dates are stored as a decimal value, you did not specify how you want to construct your int.
Do you want the actual decimal value ?
you can see the value like this
select CONVERT(float, getdate())
if you only need the date, then this can help
select convert(int, convert(datetime, convert(date, getdate())))
or
select convert(int, getdate(), 112)
Both methods will return an int value for the given date.
For 22/06/2021 this will return 44367
or if you just want to convert the formatted value, then the easiest way is this
select convert(int, Convert(CHAR(8), getdate(), 112))
For 22/06/2021 this will return 20210622

Date convert not working with style 103

I have saved my date as a nvarchar(50) datatype in SQL Server. When I run this query:
select [Client_code], Date_of_receipt
from [T_Receving]
I am getting output like this:
but I want to filter my records by particular date, so I wrote a query like this
select
convert(date, [Date_of_receipt], 103) as 'Date_of_Receipt'
from
[T_Receving]
where
convert(date, [Date_of_receipt], 103) between '2015-03-06' and '2018-05-06'
but its showing an error
Conversion failed when converting date and/or time from character string
You have to convert to datetime and then convert back to varchar
declare #dtv varchar(20) = '2018-17-04'
declare #dtvdt datetime = convert(datetime, #dtv, 103)
select #dtvdt;
select convert(varchar(20), convert(datetime, #dtv, 103), 103), #dtv
where convert(datetime, #dtv, 103) between '2015-03-06' and '2018-05-06'
You clearly have some bad data. Use try_convert():
select try_convert(DATE, Date_of_receipt, 103) as Date_of_Receipt
from T_Receving
where try_convert(DATE, Date_of_receipt, 103) between '2015-03-06' and '2018-05-06' ;
In SQL Server 2008, you have to work harder to find the culprits. You can start with:
select date_of_receipt
from T_Receving
where date_of_receipt not like '[0-3][0-9]/[0-1][0-9]/[0-9][0-9][0-9][0-9]'
This will find most instances of bad formats. If it still persists, you will have to dig deeper to find bad day or month numbers.

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

Convert nvarchar to date and Get data between two date

I'm collecting data between two date 01/12/2014 and 31/12/2014 but my sql data type in nvarchar
is my query right?
SELECT * from customer where date >= convert(datetime, '01/12/2014', 105)
AND date <= convert(datetime, '31/12/2014', 105)
Result
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
can any one solve this problem...
as I know you must separate different parts of a DATE with "-" not with "/" in format 105. here is an example:
SELECT convert(datetime, '23-10-2016', 105) -- dd-mm-yyyy
so you must rewrite your code as:
SELECT * from customer where date >= convert(datetime, '01-12-2014', 105)
AND date <= convert(datetime, '31-12-2014', 105)
The format your string are in, 'dd/mm/yyyy' is 103, not 105 (which is 'dd-mm-yyyy'). So, simply use the correct format:
SELECT *
FROM customer
WHERE [date] >= CONVERT(datetime, '01/12/2014', 103)
AND [date] <= CONVERT(datetime, '31/12/2014', 103)
If your date type is nvarchar why don't you try like this:
SELECT * FROM customer
WHERE date >= '01/12/2014'
AND date <= '31/12/2014'
Do we really need to convert?
SELECT * FROM DBO.CUSTOMER
WHERE CAST([date] AS DATE) >= '01/12/2014' AND
CAST([date] AS DATE) <= '31/12/2014'
I suggest you to use this:
(I think converting to varchar is make more sense)
SELECT *
FROM customer
WHERE CONVERT(varchar, [date], 103) BETWEEN '01/12/2014' AND '31/12/2014'
In Date and Time Styles; 103 is for with British/French standard with century (yyyy) like this dd/mm/yyyy.

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().