Timeserial not recognized built in function in MS SQL - sql

I am trying to implement an SQL query that gets records between today's fixed timing 18:00 and yesterday's fixed timing 18:00 based on a Date time column that I have in my table.
I tried this query
DECLARE #today date = GETDATE()
SELECT *
FROM mytab
WHERE datetimecolumn Between #today-1 + TimeSerial(18,0,0)
And #today + TimeSerial(18,0,0)
But, it's throwing an error Timeserial is not a recognized built-in function name.
Any ideas please?

It would be best to use the DATEADD() function to add the time to the date you want. In this example, it subtracts 6 hours from the first number to get 18:00 yesterday, and then adds 18 hours to get 18:00 today.
DECLARE #today date = GETDATE();
SELECT * FROM mytab WHERE datetimecolumn Between DATEADD(hour,-6,#today) And DATEADD(hour,18,#today);

Related

How to show Current Date as Current Date ending at 3:00:00AM in SQL

I have a task that I need to show the current date time as ending at 3:00:00 AM at current date. For example, GETDATE() returns the current date time when executes. I need to show it as 9/5/2019 3:00:00 AM instead. Below is my code:
DECLARE #END_SHIFT AS DATETIME
SET #END_SHIFT = '06:00:00 AM'
SELECT
NUMBER_ID,
GETDATE() AS CURRENT_DT,
GETDATE() - #END_SHIFT AS END_SHIFT_DATE
FROM table
My issue when running this is it does not return as ending at 3:00:00AM. Please let me know your direction.
Thanks,
H
A bit of an odd request for sure but you could simply use DATEADD.
SELECT dateadd(hour, 3, convert(datetime, convert(date, getdate())))
If you really need a "hard" time, one option is to use format()
Example
Select format(GetDate(),'yyyy-MM-dd 03:00')
Returns
2019-09-05 03:00

Need help extracting SQL data for 2 previous days

I need to run a SQL script every night that extracts data from the previous 2 days. For example: On July 9 at 1am, the script runs and needs to extract data from July 8 and July 7. On July 10 at 1am, it needs to extract data from July 9 and July 8, etc.
The script is functional, in that it correctly extracts data for a fixed date range (by including the actual date range in the script), but I don't know how to make it do the "2 days prior" part.
Figuring this out is beyond me! Can anyone provide guidance?
Using SQL Server 2014
You can do:
where datecol >= convert(date, dateadd(day, -2, getdate())) and
datecol < convert(date, getdate())
That said, I would be very wary about putting this logic directly into a query. I would create a stored procedure in SQL Server and have it take #fromdate and #todate arguments.
Then, schedule a job that does the above calculation and calls the stored procedure with the right parameters.
One day, when the server is down or the logic fails, you will appreciate having the flexibility to specify the date range yourself.
I would create three variables.
#today: is the current datetime cast to a date to set it to midnight
#startDate: first/start date where I would use the DATEADD function to subtract two days
#endDate: end date that you can subtract 1 second from today
This should get you a date range of 2019-07-07 00:00:00.000 to 2019-07-08 23:59:59.000
DECLARE #today DATETIME = CAST(GETDATE() AS DATE);
DECLARE #startDate DATETIME = DATEADD(DAY, -2, #today);
DECLARE #endDate DATETIME = DATEADD(SECOND, -1, #today);
Time is usually very critical when working with dates, make sure your start date starts at the beginning of the day and your end date ends at the very end of the day!
Your query would then look like:
SELECT *
FROM my_table
WHERE my_date_column BETWEEN #startDate AND #endDate

Extract Date And Hour Only From Date Time Field

I am running SQL Server 2008 and I have a datetime field, from this field I only want to extract the date and hour. I tried to parse out using datepart() but I think I did it incorrectly as when I attempted to string the two back together I got a number value. What I attempted was
Select Datepart(YEAR, '12/30/2015 10:57:00.000') +
Datepart(HOUR, '12/30/2015 10:57:00.000')
And what was returned was 2025 What I want to see returned is
12/30/2015 10:00:00.000
You could use DATEADD and DATEDIFF:
DECLARE #d DATETIME = '12/30/2015 10:57:00.000';
SELECT DATEADD(second,DATEDIFF(second,'1970-01-01',#d)/3600*3600 , '1970-01-01')
-- 2015-12-30 10:00:00
LiveDemo
How it works:
Get seconds difference from 1970-01-01
Divide by 3600 (integer division so the part after decimal point will be skipped)
Multiply by 3600 to get value back to full hours
Add calculated seconds number to 1970-01-01
With SQL Server 2012+ the neat way is to use DATETIMEFROMPARTS:
SELECT DATETIMEFROMPARTS(YEAR(#d), MONTH(#d), DAY(#d), DATEPART(HOUR, #d),0,0,0)
LiveDemo2

Today minus 30 days

I need to run an query/create filter, within a program, every day WHERE last_paid is TODAY - 30 and TODAY = convert(varchar,getdate(),101). The biggest issue seems to be the inflexiblity of the program to have today be anything other than convert(varchar,getdate(),101).
This is going to be a short answer because this is an incredibly easy problem. You want to use DATEADD your syntax should be something like TODAY = convert(varchar,DATEADD(DAY,-30,getdate()),101)
UPDATE: I still think you need to address the issue you have of TODAY beings stored as some sort of string. If this were a DATE datatype you wouldn't have to deal with this convert nonsense.
Am I missing something here?
DECLARE #Today DATETIME
SELECT #Today = GETDATE() - 30
SELECT #Today AS [Today - 30]
If you don't want the time, don't make it a DateTime data type, instead use DATE:
DECLARE #Today DATE
SELECT #Today = GETDATE() - 30
SELECT #Today AS [Today - 30]
For Oracle try:
TRUNC(SYSDATE) - INTERVAL '30' days

Using Derived Column to create a date value in the format YYYY-MM-01 00:00:00.000 for each row

Im having a problem with derived columns in SSIS. When in SSMS i can set a column to have a default value using the following code:
(dateadd(month,datediff(month,(0),getdate())-(1),(0)))
and when data is entered into the database it will give it the timestamp of the previous month in the following format for example:
2010-09-01 00:00:00.000
This strangely is what im looking for and trying to duplicate/produce similar using the Derived Column DFT.
So far i have:
DATEADD("mm",DATEDIFF("mm",GETDATE(),GETDATE()) - 1,GETDATE())
which produces the month succesfully but the GETDATE() is not a correct replacement for the 0's in the original code.
Does the 0's in the original code signify the start date in SQL?
Any help would be much appreciated.
Regards,
Lee
your first code fragment is "flooring" the datetime to the month (making the date the 1st of the given month with no time) the "-1" makes it the previous month. All the extra unnecessary parenthesis in this code fragment give me a headache, here is the equivalent:
dateadd(month,datediff(month,0,getdate())-1,0)
This is how to floor a datetime to different units:
--Floor a datetime
DECLARE #datetime datetime;
SET #datetime = '2008-09-17 12:56:53.430';
SELECT '0 None', #datetime -- none 2008-09-17 12:56:53.430
UNION SELECT '1 Second',DATEADD(second,DATEDIFF(second,'2000-01-01',#datetime),'2000-01-01') -- Second: 2008-09-17 12:56:53.000
UNION SELECT '2 Minute',DATEADD(minute,DATEDIFF(minute,0,#datetime),0) -- Minute: 2008-09-17 12:56:00.000
UNION SELECT '3 Hour', DATEADD(hour,DATEDIFF(hour,0,#datetime),0) -- Hour: 2008-09-17 12:00:00.000
UNION SELECT '4 Day', DATEADD(day,DATEDIFF(day,0,#datetime),0) -- Day: 2008-09-17 00:00:00.000
UNION SELECT '5 Month', DATEADD(month,DATEDIFF(month,0,#datetime),0) -- Month: 2008-09-01 00:00:00.000
UNION SELECT '6 Year', DATEADD(year,DATEDIFF(year,0,#datetime),0) -- Year: 2008-01-01 00:00:00.000
ORDER BY 1
PRINT' '
PRINT 'Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor'
PRINT 'this always uses a date less than the given date, so there will be no arithmetic overflow'
SELECT '1 Second',DATEADD(second,DATEDIFF(second,DATEADD(day,DATEDIFF(day,0,#datetime),0)-1,#datetime),DATEADD(day,DATEDIFF(day,0,#datetime),0)-1) -- Second: 2008-09-17 12:56:53.000
the second code fragment will not properly floor the datetime to the month, it will only move the date to the previous month and use the same day and time as the given datetime.
Beyond that I'm not sure what you are really asking.
here is a breakdown of what is happening in the OP's first code fragment:
select convert(datetime,0),'first datetime "0"'
select datediff(month,0,getdate()), 'months difference between the first datetime (1900-01-01) and given "getdate()"'
select datediff(month,0,getdate())-1, 'months difference between the first datetime (1900-01-01) and month previous to given "getdate()"'
select dateadd(month,datediff(month,0,getdate())-1,0), 'takes the first datetime (1900-01-01) and adds 1328 months onto that'
OUTPUT:
----------------------- ------------------
1900-01-01 00:00:00.000 first datetime "0"
----------- --------------------------------------------------------------------------------
1329 months difference between the first datetime (1900-01-01) and given "getdate()"
----------- --------------------------------------------------------------------------------------------------
1328 months difference between the first datetime (1900-01-01) and month previous to given "getdate()"
----------------------- --------------------------------------------------------------------
2010-09-01 00:00:00.000 takes the first datetime (1900-01-01) and adds 1328 months onto that
Here's what I think you may be looking for. It is an SSIS expression that gets the first day of the previous month for a given day (GETDATE() in the example).
DATEADD("mm",DATEDIFF("mm", (DT_DBTIMESTAMP)2, GETDATE()) - 1, (DT_DBTIMESTAMP)2)
I tried to simulate your SQL version of the expression, which determined the number of months between the 0 datetime and the current datetime. And, then it added the number of months to the 0 datetime.
It's not too important what the 0 datetime is, except that you wanted the 1st day of the month. In SQL the 0 datetime is 1900-01-01 00:00:00.000, so adding months automatically gives you the first day of the month. In SSIS expressions, the 0 datetime is 1899-12-30 00:00:00.000. Since you want the first day of a month, the expression above refers to the 2 datetime. So, in the expression (DT_DBTIMESTAMP)2 casts the number 2 to 1900-01-01 00:00:00.000.
month,0 makes it round down to the beginning of the month.
Can't you use your first expression if it does what you want? Or use the second expression but switch the two GETDATE()s you've added to 0. Do you get an error if you try that?
I think what you need in your derived column is this synatx:
DATEADD("mm",-1,(DT_DBTIMESTAMP)((DT_WSTR,4)DATEPART("YYYY",GETDATE()) + "-" + (DT_WSTR,2)DATEPART("mm",GETDATE()) + "-01"))