Related
I am trying to query a SQL view to show the transactions for the last business day (i.e. the day before, or the Friday if the day the query is ran is Monday).
My query looks like this:
DECLARE
#transdate AS INT;
SET #transdate = DATEADD(DAY, CASE (
DATEPART(WEEKDAY, GETDATE()) + ##DATEFIRST) % 7 WHEN 1 THEN -2 WHEN 2 THEN -3 ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
SELECT
PolicyNumber,
LossDate,
SUM(Amount),
(CASE
WHEN SUM(Amount) < 0 THEN 'Decrease'
WHEN SUM(Amount) >= 0 THEN 'Increase'
AND) AS 'New/Decrease/Increase',
Branch AS State,
tName AS Name
FROM
ViewDataBase
WHERE
CAST(CONVERT(CHAR(30), CONVERT(DATETIME, BookingDate, 105), 101) AS DATE) = CAST(CONVERT(CHAR(30), CONVERT(DATETIME, #transdate, 105), 101) AS DATE)
AND BranchNumber IS NOT NULL
GROUP BY
BookingDate,
BranchNumber,
PolicyNumber,
LossDate,
Name
I get the following error when I try to run this query:
Msg 257, Level 16, State 3, Server PMICDB01A, Procedure , Line 0
Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.
[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query. (257)
I have tried with simply CONVERT or CAST but nothing I try seems to be the correct fix. My column BookingDate is of type Datatime2, I am not sure what type transdate is as I create it. I'm assuming my WHERE clause is the problem.
EDIT: I have also tried:
(CAST(BookingDate AS date) = CAST(#transdate AS date))
This is what I started out with:
BookingDate = #transdate
I also tried:
CONVERT(DATETIME, BookingDate) = CONVERT(DATETIME, #transdate)
and
CONVERT(DATETIME, BookingDate) = #transdate
and
BookingDate = CONVERT(datetime, #transdate)
Any suggestions?
The error you are getting is not caused by the WHERE clause. If you run just the DECLARE and the SET at the top without the SELECT, you will get the conversion error.
To correct, at the very top, first declare #transdate as a datetime:
DECLARE
#transdate AS datetime;
Then try to run just the DECLARE and SET again to see if you get an error or not. If not, then you can add back the SELECT and see if it returns results. It looks like you can simplify your WHERE clause with:
WHERE CONVERT(DATE,BookingDate) = CONVERT(DATE,#transdate)
AND BranchNumber IS NOT NULL
The conversion to DATE in the WHERE clause is just in case the BookingDate includes a time.
I have a query that runs once a day that I would like to share however I need to remove the part where the other users in my team will have to edit it. Essentially, it's run Monday thru Friday. I want, if today is Monday, give me the last 3 days worth of data. Any other day, just give me yesterday's data.
So far this is what I have:
Update: They are all strings, so now I get the following error.
"Incorrect syntax near the keyword 'BETWEEN'."
DECLARE #daychecker varchar(max) = FORMAT(GETDATE(), 'dddd')
DECLARE #daterange0 varchar(max)
DECLARE #daterange1 varchar(max) = FORMAT(GETDATE()-3, 'yyyy-MM-dd')
DECLARE #daterange2 varchar(max) = FORMAT(GETDATE()-1, 'yyyy-MM-dd')
IF #daychecker = 'Wednesday'
BEGIN
SET #daterange0 = BETWEEN #daterange1 AND #daterange2
END
ELSE
BEGIN
SET #daterange0 = FORMAT(GETDATE()-1, 'yyyy-MM-dd')
END
SELECT #daterange0;
The result for today as an example should return yesterday's date. But that doesn't work. I will consider all options including hardcoding some sort of master start date that we can count from like maybe the start of the year or something.
You're much better off defining 2 dates, a start date and end date, and filtering your query based on them. EDIT: I'm now unsure if you want actual dates for filtering data, or a label for a report. I modified my answer to include the latter, use whichever you want and ignore the other ...
DECLARE #DateStart DATE
DECLARE #DateEnd DATE
DECLARE #LableRange varchar(max)
SELECT DATEPART(WEEKDAY, GETDATE()) --Sun=1, Mon=2, ...
IF DATEPART(WEEKDAY, GETDATE()) = 2 BEGIN
SET #DateStart = DATEADD (DAY, -5,GETDATE())
SET #DateEnd = DATEADD (DAY, -2,GETDATE())
SET #LableRange = CONCAT(FORMAT(#DateStart, 'yyyy-MM-dd'), ', '
, FORMAT(DATEADD(day,1,#DateStart), 'yyyy-MM-dd'), ', '
, FORMAT(DATEADD(day,2,#DateStart), 'yyyy-MM-dd'))
-- or maybe this format is better
--SET #LableRange = CONCAT('BETWEEN '
--, FORMAT(#DateStart, 'yyyy-MM-dd'), ' AND '
--, FORMAT(DATEADD(day,2,#DateStart), 'yyyy-MM-dd'))
END ELSE BEGIN
SET #DateStart = DATEADD (DAY, -1,GETDATE())
SET #DateEnd = GETDATE()
SET #LableRange = FORMAT(#DateStart, 'yyyy-MM-dd')
END
SELECT #LableRange
SELECT * FROM SomeTable as T
WHERE T.TestDate < #DateEnd AND T.TestDate >= #DateStart
Note that this works even if the date you are filtering on is a datetime instead of pure date.
I come in to work 6.30am, and need to audit what happened from 5pm when I left to 6.30am this morning. I have used code to search 13.5 hours back from any given time:
SELECT * FROM TRANSACTION_HISTORY
WHERE TRANSACTION_HISTORY.ACTIVITY_DATE_TIME > (SELECT DATEADD(hour,-13.5,(SELECT MAX (TRANSACTION_HISTORY.ACTIVITY_DATE_TIME) FROM TRANSACTION_HISTORY)))
Problem is if I run query later, I lose time from the start, eg. If I run query at 7am, I only get results from 5.30pm onwards. Rather than change criteria every day, I wanted to able to search from 6.30am of the current day, back to 5.30pm of the previous day. Can this be done?
Normally, I don't advise using between for datetime, because the boundary conditions can cause confusion. I don't think that is the case.
Here is one method:
SELECT *
FROM TRANSACTION_HISTORY th
WHERE th.ACTIVITY_DATE_TIME between cast(cast(getdate() -1 as date) as datetime) + 17.5/24.0
cast(cast(getdate() as date) as datetime) + 6.5/24.0;
The expression cast(cast(getdate() as date) as datetime) is truncating the datetime value to midnight. As a datetime, SQL Server lets you add a number which is understood as a fraction of a day. Hence, 17.5/24 represents "5:30". This addition doesn't work for the date data type.
You can do this.
DECLARE #dt datetime
DECLARE #dt1 datetime
DECLARE #dt2 datetime
SET #dt = CONVERT(datetime, CONVERT(VARCHAR(10), getdate(), 101 ), 101)
SET #dt1 = dateadd(mi, 30, dateadd(hh, 6, #dt))
SET #dt2 = dateadd(mi, -27*30, #dt1)
SELECT #dt1 as StartDate, #dt2 as EndDate
For additional details what this script does you may check these pages.
http://technet.microsoft.com/en-us/library/ms174450%28v=sql.105%29.aspx
http://technet.microsoft.com/en-us/library/ms186819%28v=sql.105%29.aspx
i have an ssis Package which runs on business days (mon-Fri). if i receive file on tuesday , background(DB), it takes previous business day date and does some transactions. If i run the job on friday, it has to fetch mondays date and process the transactions.
i have used the below query to get previous business date
Select Convert(varchar(50), Position_ID) as Position_ID,
TransAmount_Base,
Insert_Date as InsertDate
from tblsample
Where AsOfdate = Dateadd(dd, -1, Convert(datetime, Convert(varchar(10), '03/28/2012', 101), 120))
Order By Position_ID
if i execute this query i'll get the results of yesterdays Transactios. if i ran the same query on monday, it has to fetch the Fridays transactions instead of Sundays.
SELECT DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
WHEN 'Sunday' THEN -2
WHEN 'Monday' THEN -3
ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
I prefer to use DATENAME for things like this over DATEPART as it removes the need for Setting DATEFIRST And ensures that variations on time/date settings on local machines do not affect the results. Finally DATEDIFF(DAY, 0, GETDATE()) will remove the time part of GETDATE() removing the need to convert to varchar (much slower).
EDIT (almost 2 years on)
This answer was very early in my SO career and it annoys me everytime it gets upvoted because I no longer agree with the sentiment of using DATENAME.
A much more rubust solution would be:
SELECT DATEADD(DAY, CASE (DATEPART(WEEKDAY, GETDATE()) + ##DATEFIRST) % 7
WHEN 1 THEN -2
WHEN 2 THEN -3
ELSE -1
END, DATEDIFF(DAY, 0, GETDATE()));
This will work for all language and DATEFIRST settings.
This function returns last working day and takes into account holidays and weekends. You will need to create a simple holiday table.
-- =============================================
-- Author: Dale Kilian
-- Create date: 2019-04-29
-- Description: recursive function returns last work day for weekends and
-- holidays
-- =============================================
ALTER FUNCTION dbo.fnGetWorkWeekday
(
#theDate DATE
)
RETURNS DATE
AS
BEGIN
DECLARE #importDate DATE = #theDate
DECLARE #returnDate DATE
--Holidays
IF EXISTS(SELECT 1 FROM dbo.Holidays WHERE isDeleted = 0 AND #theDate = Holiday_Date)
BEGIN
SET #importDate = DATEADD(DAY,-1,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
--Satruday
IF(DATEPART(WEEKDAY,#theDate) = 7)
BEGIN
SET #importDate = DATEADD(DAY,-1,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
--Sunday
IF(DATEPART(WEEKDAY,#theDate) = 1)
BEGIN
SET #importDate = DATEADD(DAY,-2,#theDate);
SET #importDate = (SELECT dbo.fnGetWorkWeekday(#importDate))
END
RETURN #importDate;
END
GO
Then how about:
declare #dt datetime='1 dec 2012'
select case when 8-##DATEFIRST=DATEPART(dw,#dt)
then DATEADD(d,-2,#dt)
when (9-##DATEFIRST)%7=DATEPART(dw,#dt)%7
then DATEADD(d,-3,#dt)
else DATEADD(d,-1,#dt)
end
The simplest solution to find the previous business day is to use a calendar table with a column called IsBusinessDay or something similar. The your query is something like this:
select max(BaseDate)
from dbo.Calendar c
where c.IsBusinessDay = 0x1 and c.BaseDate < #InputDate
The problem with using functions is that when (not if) you have to create exceptions for any reason (national holidays etc.) the code quickly becomes unmaintainable; with the table, you just UPDATE a single value. A table also makes it much easier to answer questions like "how many business days are there between dates X and Y", which are quite common in reporting tasks.
You can easily make this a function call, adding a second param to replace GetDate() with whatever date you wanted.
It will work for any day of the week, at any date range, if you change GetDate().
It will not change the date if the day of week is the input date (GetDate())
Declare #DayOfWeek As Integer = 2 -- Monday
Select DateAdd(Day, ((DatePart(dw,GetDate()) + (7 - #DayOfWeek)) * -1) % 7, Convert(Date,GetDate()))
More elegant:
select DATEADD(DAY,
CASE when datepart (dw,Getdate()) < 3 then datepart (dw,Getdate()) * -1 + -1 ELSE -1 END,
cast(GETDATE() as date))
select
dateadd(dd,
case DATEPART(dw, getdate())
when 1
then -2
when 2
then -3
else -1
end, GETDATE())
thanks for the tips above, I had a slight variant on the query in that my user needed all values for the previous business date. For example, today is a Monday so he needs everything between last Friday at midnight through to Saturday at Midnight. I did this using a combo of the above, and "between", just if anyone is interested. I'm not a massive techie.
-- Declare a variable for the start and end dates.
declare #StartDate as datetime
declare #EndDate as datetime
SELECT #StartDate = DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
WHEN 'Sunday' THEN -2
WHEN 'Monday' THEN -3
ELSE -1 END, DATEDIFF(DAY, 0, GETDATE()))
select #EndDate = #StartDate + 1
select #StartDate , #EndDate
-- Later on in the query use "between"
and mydate between #StartDate and #EndDate
Well this is my case: I have an input date X (dd-mm-yyyy), and I want to count the number of days between it with the year part is changed into current year and today's date in SQL. I t comes with the following condition, after the year is changed temporarily: (Here's my current idea of the logic)
- If date X is earlier than today, then difference = datediff(X,now), with the X year is current year
- If date X is later than today, then difference = datediff(X,now), with the X year is one year before
Sample case:
1st case: The input date is 6-6-1990. Today (automatically generated) is 22-8-2011. Then the difference will be = datediff(6-6-2011,22-08-2011)
2nd case: The input date is 10-10-1990. Today (automatically generated) is 22-8-2011. Then the difference will be = datediff(10-10-2010,22-08-2011)
Any idea how to do this in SQL (in SQL Server)? Or is there any other more simple alternatives for this problem? I'd also like this to be done in the query and not using a stored procedure or function
Sorry if there's already a similar question, I just don't know the exact keyword for this problem :( if there's a question like this previously, feel free to direct me there.
Thanks in advance
Here is the implementation (if I understood the logic you need correctly):
USE YourDbName
GO
CREATE FUNCTION YearPartDiff (#date datetime)
RETURNS int
AS
BEGIN
DECLARE #dateCurrentYear datetime
SET #dateCurrentYear = DATEADD(year, YEAR(GETDATE()) - YEAR(#date), #date)
DECLARE #result int
IF #dateCurrentYear < GETDATE()
SET #result = ABS(DATEDIFF(day, #dateCurrentYear, GETDATE()))
ELSE
SET #result = ABS(DATEDIFF(day, DATEADD(year, -1, #dateCurrentYear), GETDATE()))
RETURN(#result)
END
GO
And the example of usage:
USE YourDbName
GO
DECLARE #someDate datetime
SET #someDate = '2011-06-06'
SELECT dbo.YearPartDiff(#someDate) /*returns 77*/
SET #someDate = '2010-10-10'
SELECT dbo.YearPartDiff(#someDate) /*returns 316*/
Basically, #Andrei's solution, but in a single statement:
SELECT
DayDiff = DATEDIFF(
DAY,
DATEADD(YEAR, CASE WHEN LastOcc > GETDATE() THEN -1 ELSE 0 END, LastOcc),
GETDATE()
)
FROM (
SELECT LastOcc = DATEADD(YEAR, YEAR(GETDATE()) - YEAR(#InputDate), #InputDate)
) s
This seems to do the job
SELECT DATEDIFF(DAY, CONVERT(DATETIME, N'2011-06-06'), CONVERT(DATETIME, N'2011-08-22'))
So the basic syntax is
SELECT DATEDIFF(DAY, CONVERT(DATETIME, N'yyyy-mm-dd'), CONVERT(DATETIME, N'yyyy-mm-dd '))
Alternatively, you can use GETDATE() instead of the string for today's date
I have used "SELECT DATEDIFF( D, "+myDate+", GETDATE())" in my code, on SQL Server 2005. It works for me. The value myDate of course would be the DateTime input value.
you should try this query:
create table #T (inp_date datetime)
insert #T values ('06-06-1990')
insert #T values ('08-22-1990')
insert #T values ('10-10-1990')
--select * from #T
select inp_date, GETDATE(),
CASE
WHEN DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE()),inp_date) <= GETDATE()
THEN DATEDIFF(dd,DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE()),inp_date),GETDATE())
ELSE DATEDIFF(dd,DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE())-1,inp_date),GETDATE())
END
from #T