How to print a week in date in SQL - sql

I use sql server.
what I've been doing is this:
LEFT(yearmonth,4) + RIGHT( '0' + CONVERT(VARCHAR, DATEPART(WK, yearmonthdate)), 2)
yearmonth = '201601'
and
yearmonthdate = '20160101' through '20160131'
which prints out like this:
201601
201602
but I want to print out like the following:
20160101-20160102
20160103-20160109
respectively.
How do I accomplish that?
I've on google but I couldn't get to print out like that.
Thank you in advance.

DECLARE #Table TABLE (Col1 INT, Col2 DATETIME)
DECLARE #StartDT DATETIME
DECLARE #tempDT DATETIME
DECLARE #EndDT DATETIME
SET #StartDT = DATEFROMPARTS(YEAR(getdate()),MONTH(getdate()),1)
SET #EndDT = EOMONTH (#StartDT)
set #tempDT=#StartDT
WHILE #StartDT < #EndDT
BEGIN
PRINT
CONVERT(VARCHAR,cast(#tempDT as date))
+ ' - ' +
convert(VARCHAR,cast(DATEADD(dd, 7-(DATEPART(dw, #StartDT)), #StartDT) as date))
SET #StartDT = DATEADD(dd, 7-(DATEPART(dw, #StartDT)), #StartDT)
SET #tempDT = DATEADD(dd,1,#StartDT)
SET #StartDT = DATEADD(WEEK,1,#StartDT)
END
PRINT
CONVERT(VARCHAR,cast(#tempDT as date))
+ ' - ' +
convert(VARCHAR,cast(#EndDT as date))

Related

How to create a complete datetime from a month and year passed as parameters

I want to let a user select a month and a year in a report from textbox and use these parameters to create first day in the month and the last one for my server parameters 'DateFrom' and 'DateTo', so I can use these as filters.
I've tried:
#DateFrom DATETIME,
#DateTo DATETIME,
#Month NVARCHAR(MAX) = NULL,
#Year NVARCHAR(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
SET #DateFrom = '1.' & #Month & #Year
SET #DateTo = DATEADD(m, 1, DATEADD(s, -1, #DateFrom))
Any help would be aprreciated.
Try This
SET #DateFrom = SELECT CAST(#Year + '-' + #Month + '-' + '01' AS DATE)
SET #DateTo = DATEADD(m, 1, DATEADD(s, -1, #DateFrom))

How to add date and time in SQL Server

I have two variables #date of type datetime and #time of type time. I want to add both to get another datetime variable. And I want to perform further calculations on it.
Ex:
Declare #date datetime
Declare #time time
I want something like this
#date = #date + #time (but not concatenation)
SELECT #Startdate = DATEADD(DAY, -1, #date )
Is there any way?
You can tranform your time to seconds and add them to your datetime value:
DECLARE #datetime DATETIME = GETDATE(),
#time TIME = '01:16:24',
#timeinseconds INT
PRINT 'we add ' + CAST(#time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,#datetime,120)+ ':'
SELECT #timeinseconds = DATEPART(SECOND, #time)
+ DATEPART(MINUTE, #time) * 60
+ DATEPART(HOUR, #time) * 3600
SET #datetime = DATEADD(SECOND,#timeinseconds,#datetime)
PRINT 'The result is: ' + CONVERT(VARCHAR,#datetime,120)
Output:
we add 01:16:24 to 2015-07-17 09:58:45:
The result is: 2015-07-17 11:15:09
The only thing you are missing is that #time needs to be cast back to a datetime before adding to #date.
declare #date datetime = '2022-05-26'
declare #time time = '09:52:14'
declare #Startdate datetime
set #date = #date + convert(datetime,#time)
SELECT #Startdate = DATEADD(DAY, -1, #date)
Produces:
If you need to take only date part from #date and time part from #time - can convert your #date and #time to strings, concatenate the values and convert back to datetime:
select cast(convert(nvarchar(20), #date, 104) + ' ' +
convert(nvarchar(20), #time, 108) as datetime2)
Or, alternatively, if you need to add time to datetime value, you can do something like:
select dateadd(ms,
datepart(ms, #time),
dateadd(ss,
datepart(ss, #time),
dateadd(mi,
datepart(mi, #time),
dateadd(hh, datepart(hh, #time), #date))))
First of all convert #date and #time variables to NVARCHAR(), then concat them and after It convert It to DATETIME datatype. After It you can use DATEADD function on It. Try in following:
DECLARE #date DATETIME
DECLARE #time TIME
SET #date = GETDATE()
SET #time = '10:12:13'
SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), #date, 110) + ' ' +
CONVERT(NVARCHAR(20), #time, 108) AS DATETIME))
OUTPUT (Today day -1 + time '10:12:13'):
2015-07-16 10:12:13.000
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine:
declare #date datetime
declare #time time
set #date = '20150717'
set #time = '12:34:56'
set #date = #date + #time
select #date, DATEADD(DAY,-1,#date)
See SQL Fiddle
If the problem is that #date contains also time part, you can use:
set #date = convert(datetime, convert(date, #date)) + #time
Your code is correct.
DECLARE #date DATETIME = '1/1/2020'
DECLARE #time TIME = '1:00 pm'
DECLARE #Startdate DATETIME
SET #date = #date + #time
SELECT #Startdate = DATEADD(DAY, -1, #date)
#date = 2020-01-01 13:00:00.000
#Startdate = 2019-12-31 13:00:00.000
It isn't concatenating, it is adding them together. The time on #date is 0:00:00.000, so it might appear to be concatenating them. But change #date to '1/1/2020 1:00 am' and then:
#date = 2020-01-01 14:00:00.000
#Startdate = 2019-12-31 14:00:00.000

How to get full date from the given month and year in SQL SERVER?

I have following script where I need to get the full date
DECLARE #BeginDate DateTime
DECLARE #EndDate DateTime
Declare #month int
Declare #year int
set #month = 6
set #year = 2014
Select beginDate = CAST(#month AS VARCHAR(10)) + '/01/' + CAST(#year AS VARCHAR(10))
SELECT endDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #beginDate) + 1, 0))
This script returns endDate as null. How do I get full endDate by passing only Date (not time)?
I think you forgot to put # sign in front of the variables. If you change the last two lines with the following:
Select #beginDate = CAST(#month AS VARCHAR(10)) + '/01/' + CAST(#year AS VARCHAR(10))
SELECT #endDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #beginDate) + 1, 0))
it should work. By putting "select #enddate" at the end, I got 2014-06-30 00:00:00.000 .
Well I found it.
DECLARE #BeginDate DateTime
DECLARE #EndDate DateTime
Declare #month int
Declare #year int
set #month = 7
set #year = 2014
Select #beginDate = CAST(#month AS VARCHAR(10)) + '/01/' + CAST(#year AS VARCHAR(10))
SELECT endDate = DATEADD(d, -DAY(DATEADD(mm, 1, #beginDate)), DATEADD(m, 1, #BeginDate))
source

SQL date selection as NULL, After, Before, Between

Requirement: select by date as After, Before, Between or all if null
I'm using SQL Server 2008
This is my attempt but I'm getting syntax errors on code that is valid used outside of the case.
Is there a better method?
using case what is the correct syntax?
declare #StartDate datetime;
declare #EndDate datetime;
SET #EndDate = GETDATE();
SET #StartDate = DATEADD(year, -2, GETDATE());
select *
from ArCustomer
where CAST(Customer as int) > 1000
AND
CASE WHEN #StartDate IS NOT NULL AND #EndDate IS NOT NULL THEN
ArCustomer.DateLastSale BETWEEN #StartDate AND #EndDate
WHEN #StartDate IS NULL AND #EndDate IS NOT NULL THEN
ArCustomer.DateLastSale < #EndDate
WHEN #StartDate IS NOT NULL AND #EndDate IS NULL THEN
ArCustomer.DateLastSale > #StartDate
END;
Alternately, you could not restrict by the date parameter if it is NULL:
SELECT *
FROM ArCustomer ac
WHERE
CAST(ac.Customer as int) > 1000
AND (ac.DateLastSale >= #StartDate OR #StartDate IS NULL)
AND (ac.DateLastSale <= #EndDate OR #EndDate IS NULL)
Or... you can handle the NULL by treating it as the low-end or high-end date:
SELECT *
FROM ArCustomer ac
WHERE
CAST(ac.Customer as int) > 1000
AND ac.DateLastSale BETWEEN ISNULL(#StartDate, '1900-01-01')
AND ISNULL(#EndDate, '9999-12-31')
EDIT:
There could be a difference in the execution plan between these two approaches, so you might try both methods and see if one out-performs the other...
WHERE CAST(Customer as int) > 1000 AND
(#StartDate IS NULL OR #StartDate <= ArCustomer.DateLastSale) AND
(#EndDate IS NULL OR ArCustomer.DateLastSale <= #EndDate)
Please note that the below query should have * avoided and the specific column names should be mentioned.
declare #StartDate datetime;
declare #EndDate datetime;
SET #EndDate = GETDATE();
SET #StartDate = DATEADD(year, -2, GETDATE());
Declare #SQL Varchar(1000)
Set #SQL = 'select ColumnName
from ArCustomer
where CAST(Customer as int) > 1000
AND'
if(#StartDate IS NOT NULL AND #EndDate IS NOT NULL)
Begin
Set #SQL = #SQL + ' ArCustomer.DateLastSale BETWEEN ''' + Convert(varchar, #StartDate) +
''' AND ''' + Convert(varchar, #EndDate) + ''''
End
else if(#StartDate IS NULL AND #EndDate IS NOT NULL)
Begin
Set #SQL = #SQL + ' ArCustomer.DateLastSale < ''' + Convert(varchar, #EndDate) + ''''
End
else
Set #SQL = #SQL + ' ArCustomer.DateLastSale > ''' + Convert(varchar, #StartDate) + ''''
exec(#SQL)
Considered all cases.

SQL: How to produce next date given month and day

In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day.
So if I had Month = 9, Day = 7 it would produce 9/7/2009.
If I had Month 1, Day 1 it would produce 1/1/2010.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse).
declare #month tinyint
declare #day tinyint
set #month = 9
set #day = 1
declare #date datetime
-- this could be inlined if desired
set #date = convert(char(4),year(getdate()))+'0101'
set #date = dateadd(month,#month-1,#date)
set #date = dateadd(day,#day-1,#date)
if #date <= getdate()-1
set #date = dateadd(year,1,#date)
select #date
Alternatively, to create a string in YYYYMMDD format:
set #date =
right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),#month),2)
+ right('00'+convert(char(2),#day),2)
Another method, which avoids literals all together:
declare #month tinyint
declare #day tinyint
set #month = 6
set #day = 24
declare #date datetime
declare #today datetime
-- get todays date, stripping out the hours and minutes
-- and save the value for later
set #date = floor(convert(float,getdate()))
set #today = #date
-- add the appropriate number of months and days
set #date = dateadd(month,#month-month(#date),#date)
set #date = dateadd(day,#day-day(#date),#date)
-- increment year by 1 if necessary
if #date < #today set #date = dateadd(year,1,#date)
select #date
Here is my sql example so far. I don't really like it though...
DECLARE #month tinyint,
#day tinyint,
#date datetime
SET #month = 1
SET #day = 1
-- SET DATE TO DATE WITH CURRENT YEAR
SET #date = CONVERT(datetime, CONVERT(varchar,#month) + '/' + CONVERT(varchar,#day) + '/' + CONVERT(varchar,YEAR(GETDATE())))
-- IF DATE IS BEFORE TODAY, ADD ANOTHER YEAR
IF (DATEDIFF(DAY, GETDATE(), #date) < 0)
BEGIN
SET #date = DATEADD(YEAR, 1, #date)
END
SELECT #date
Here's a solution with PostgreSQL
your_date_calculated = Year * 10000 + Month * 100 + Day
gives you a date like 20090623.
select cast( cast( your_date_calculated as varchar ) as date ) + 1
Here's my version. The core of it is just two lines, using the DATEADD function, and it doesn't require any conversion to/from strings, floats or anything else:
DECLARE #Month TINYINT
DECLARE #Day TINYINT
SET #Month = 9
SET #Day = 7
DECLARE #Result DATETIME
SET #Result =
DATEADD(month, ((YEAR(GETDATE()) - 1900) * 12) + #Month - 1, #Day - 1)
IF (#Result < GETDATE())
SET #Result = DATEADD(year, 1, #Result)
SELECT #Result