Find Weekending Date (Friday) based on another Date column in SQL Server? - sql-server

I am trying to replicate a weekending query that I use in access, in SQL Server and not having much luck with getting ti to perform how I need it to.
Basically, I need to find the week-ending date (with the week-ending date being a Friday) of another date column and would like it formatted to be American short date (eg. 10/06/2017).
I use the below in Access which gets me the result I need. So if the ACTUAL_DATE is 10/03/2017, the result I would need is 10/06/2017.
Actual_Date_WE: [ACTUAL_DATE] + 7 - Weekday([ACTUAL_DATE], 7)
Thank you! :)

try this
Declare #Date date
SET #Date = '2017-10-01'
select dateadd(day, (7+(6 - datepart(WEEKDAY, #date))) %7, #date)

declare #i date='10/3/2017'
declare #Friday int=6
SELECT convert(varchar,dateadd(day,(#Friday-DATEPART(dw,#i)),#i) ,110)

Related

How to find difference in days from DD-MM-YYYY formatted dates in SQL Server?

I want to find the difference between two dates in DD-MM-YYYY format. For example, I have 2 dates 29-10-2018 and 29-11-2018. I want to find the difference in number of days between those two dates (30 days) in SQL Server.
You can change the date format of current session and then use DateDiff function.
SET DATEFORMAT 'dmy'
SELECT DATEDIFF(DAY, '29-10-2018', '29-11-2018')
I will check more about Set DateFormat before adding this to Production code.
That changes the SESSION date format, not the DATABASE.
[Note from Previous Post: This is often not the way to solve the problem of interpreting dates. Datetimes should not be stored a strings if you can avoid it (use a datetime or date column instead). If you have to store in a string form, use an ISO 8601 format which is basically of the form YYYYMMDD]
Use DATEDIFF
SELECT DATEDIFF(day, '2018-10-29 00:00:00.000', '2010-11-29 00:00:00.000')
declare #date1 varchar(10),#date2 varchar(10)
set #date1 = '01-11-2018'
set #date2 = '28-11-2018'
select
datefromparts(
right(left(#date2 ,10),4),
substring(left(#date2 ,10),4,2),
left(left(#date2 ,10),2)
)
select
DATEDIFF
(
DAY,
datefromparts( right(left(#date1 ,10),4),
substring(left(#date1 ,10),4,2),
left(left(#date1 ,10),2)
),
datefromparts( right(left(#date2 ,10),4),
substring(left(#date2 ,10),4,2),
left(left(#date2 ,10),2)
)
)

Convert DDMMYYYY to YYYYMMDD date format in sql server?

I have a date in table as "26052016" in format DDMMYYYY
I want to convert this date to "YYYYMMDD" format.
Any idea
I have tried this method
select CONVERT(varchar(8),[doc-date],112) FROM C034_PDK_ParallelBillingSourceExtract
But this is gives me the same date as a result.
Please help me
I can find this way, i don't know if any other way exist or not..
declare #date nvarchar(max)='01052016'
select convert(varchar(8),cast(CONCAT(SUBSTRING(#date,3,2),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,5,4)) as date),112)as [YYYYMMDD]
Clear Code:
declare #date nvarchar(max)='01052016'
declare #date1 date
set #date1 =cast(CONCAT(SUBSTRING(#date,3,2),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,5,4)) as date)
select convert(varchar(8),#date1,112)as [YYYYMMDD]
If you are using Sql version< 2012 then you need to skip CONCAT and use + for string concatination.
SELECT CONVERT(VARCHAR(8), doc-date, 112) AS [YYYYMMDD] from
C034_PDK_ParallelBillingSourceExtract
Check ... this should work correctly.
Thanks
SELECT CONVERT(VARCHAR(8), '26052016', 112) AS [YYYYMMDD] from
C034_PDK_ParallelBillingSourceExtract
Try like this,
SELECT substring([doc-date], 5, 4) + substring([doc-date], 3, 2) + substring([doc-date], 1, 2) AS [YYYYMMDD]
FROM C034_PDK_ParallelBillingSourceExtract
There are differet ways to do it.
The best way is to use substring method as you know the character positions are going to remain same.
For Example
Suppose your date is - 31122015
Pick the portions of date using substring method and concatenate them
select SUBSTRING('31122015',5,4) + SUBSTRING('31122015',3,2) + SUBSTRING('31122015',1,2)
The result would be - 20153112
Since SQL Server 2016 we have a couple of handy tools for this:
Use DATEFROMPARTS and SUBSTRING to convert odd date formats from any arrangement within a Varchar to an actual date:
SELECT DATEFROMPARTS(SUBSTRING('31122015',5,4), SUBSTRING('31122015',3,2), SUBSTRING('31122015',1,2))
Use FORMAT to Convert an actual date to YYYYMMDD:
SELECT FORMAT(MyDate, 'yyyyMMdd')
watch out for the yyyyMMdd, that's the only part of MS SQL that is case-sensitive. Lower case mm is "minutes" and upper case MM is "Month", upper case YYYY or DD is nothing, and will just add letters to your output!

Query epoch time using SQL Server to find date range

I have to query an SQL Server database and the table's values use Epoch time (an int. Here's an example - 1438005018). I am wondering how I can write a query so that I can say the following...
select
*
from
tablename
where
epochdate between 'yesterday at 12:00' and 'today at 12:00' --this is the part I'm not sure about.
Ideally, if it's easy, I'd like the query to use non-epoch logic as Epoch time confuses the crap out of me. Maybe there's a quick way of converting in SQL Server?
I posted a link above in the comments that may be a more practical solution if you're able to deploy functions in the database you're working with, but if you're only able to query, this is an option to try as well (this assumes SQL Server 2008 and above):
declare #todayepoch bigint, #yesterdayepoch bigint;
select #todayepoch =
cast((cast(dateadd(hour, 12,
cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
- cast(cast('1970-01-01' as datetime) as decimal(24,10)))
*60.0*60.0*24.0 as int), -- + 18000, --Eastern time
#yesterdayepoch =
cast((cast(dateadd(hour, -12,
cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
- cast(cast('1970-01-01' as datetime) as decimal(24,10)))
*60.0*60.0*24.0 as int) -- + 18000 --Eastern time
select #todayepoch, #yesterdayepoch
select
*
from
tablename
where
epochdate between #yesterdayepoch and #todayepoch
I used UTC above as a presumption of comparing based on UTC times, but you could also compare to your time zone, with the appropriate addition/subtraction of your time zone difference in seconds (e.g., add 18000 to each variable to get noon in Eastern Standard Time).
You can test your results by using http://www.epochconverter.com/ to compare your values in your variables.
You query would look like the following:
DECLARE #dt_from DATETIME;
DECLARE #dt_to DATETIME;
SELECT
#dt_from=DATEADD(HH,-12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME)), -- strip time of current UTC date/time, and subtract 12 hrs
#dt_to=DATEADD(HH,+12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME)); -- strip time of current UTC date/time, and add 12 hrs
SELECT
*
FROM
tablename
WHERE
epochdate BETWEEN DATEDIFF(s,'1970-01-01',#dt_from) AND DATEDIFF(s,'1970-01-01',#dt_to);

Datepart() is there any way to use a variable for the datepart interval

I'm creating a SQL server stored procedure that is doing a lot of filtering based on the current week. Rather than passing in a start and end date, I am passing in a single date and using Datepart() to filter out the week.
Where DATEPART(WEEK, cd.TurninDate) = DATEPART(WEEK, #StartDate)
and DATEPART(YEAR, cd.TurninDate) = DATEPART(YEAR, #StartDate)
Trying top be proactive, I can see managers asking for this to be run Monthly or Quarterly as well as Weekly. I'd rather not have a stored Proc for each version if I can help it. I want to pass in the frequency and the date but it doesn't seem to work.
I tried:
Where DATEPART(#Freq, cd.TurninDate) = DATEPART(#Freq, #StartDate)
and DATEPART(YEAR, cd.TurninDate) = DATEPART(YEAR, #StartDate)
but I get an error on the #Freq not being recognized as an interval.
Does anyone know a way I can get around that?
There is no way to use a variable but you can work around it:
case
when #part = 'YEAR' THEN DATEPART(YEAR, cd.TurninDate)
when #part = 'WEEK' THEN DATEPART(WEEK, cd.TurninDate)
...
END
The design of the SQL/T-SQL language is lacking as you can see.
The MSDN information is pretty clear
datepart
Is the part of date (a date or time value) for which an integer will be returned. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid
https://msdn.microsoft.com/en-us/library/ms174420.aspx
But to get around this you can create a dynamic SQL and fill in that part with a variable.
select datepart(year,GETDATE())
declare #DateType varchar(max);
set #DateType = 'YEAR';
declare #datemanip varchar(max);
set #datemanip = 'select datepart(' + #DateType + ',GETDATE())';
execute( #datemanip );
Both of these statements will yield the same result. You can then put this in your stored procedure and pass in #DateType as parameter.

SQL Server 2008 script - how to to acquire current date from system and store it into a date column

Hey fellas, I'm having difficulty obtaining only the date from the system and inserting it into a column, is there a built-in function that can acquire it?
On top of that, how do I add years to the current date?
I know I'm pushing it right now, but I'm also wondering what's the format for the date datatype?
Because sometimes I'd like to manually insert values into a column with that type in mind.
Any help would greatly be appreciated.
Thanks.
To get date only (SQL Server 2008 only) CAST to date type
SELECT CAST(GETDATE() AS date)
To add years, use DATEADD
SELECT DATEADD(year, 2, CAST(GETDATE() AS date))
Formats: use yyyymmdd or ISO yyyy-mm-dd (for newer datetime types) for safety.
Read this for everything about date+time in SQL Server
To add a year to the current date, look at the dateadd() function.
To just get the date from sql w/o the time, you can do this:
DECLARE #Date DATETIME
SELECT #Date = CONVERT(VARCHAR, GETDATE(), 101)
SELECT #Date
Sql will implicity convert the VARCHAR back to DATETIME. Look up the CONVERT function in BOL and it will give you all kinds of different styles for the 3rd parameter.
Bender

Resources