how can I convert a date var to a number is sql? - sql

I have this statements
SELECT #startdate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -7) -- Monday of previous week
SELECT #enddate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1) -- Sunday of previous week
and I want to convert #startdate and #enddate to numbers in the following format 'yyyymmdd'

SELECT CONVERT(nvarchar(8), #StartDate, 112)
Will convert 2014-03-31 to 20140331

The easiest way is to use year(), month(), and day():
select #startdate = year(getdate())*10000 + month(getdate()) * 100 + day(getdate())

Use CONVERT
declare #enddate smalldatetime
SELECT #enddate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1)
select convert(varchar(30), #enddate, 112)

This will work for you:
SELECT CAST(DATEPART(yyyy,#startdate) AS VARCHAR(4)) +
RIGHT('0' + CAST(DATEPART(mm,#startdate) AS VARCHAR(2)),2) +
RIGHT('0' + CAST(DATEPART(dd,#startdate) AS VARCHAR(2)),2)
But this is better:
SELECT CONVERT(nvarchar(8), #StartDate, 112)

Related

Why Week conversion failed in SQL Server in my case?

I am trying to convert week of the date based on my criteria.
My date condition: if my #date is less than 4 AM, then #date - 1, else #date
declare #dates datetime
set #dates = '2019-01-01 03:59:59'
select
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then convert(varchar, dateadd(day, -1, #dates), 103)
else convert(varchar, #dates, 103)
end BusinessDate
Output:
31/12/2018 // as expected
Now I want to find the week number of the output. So I tried
declare #dates datetime
set #dates = '2019-01-01 03:59:59'
select
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then convert(varchar, dateadd(day, -1, #dates), 103)
else convert(varchar, #dates, 103)
end BusinessDate,
case
when convert(varchar(26), #dates, 108) <= '04:00:00'
then datepart(week, convert(datetime, convert(varchar, dateadd(day, -1, #dates), 103)))
else datepart(week, convert(datetime, convert(varchar, #dates, 103)))
end weeks
But I get this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Just subtract four hours:
select datepart(week,
dateadd(hour, -4, #dates)
)

Get calendar week id in sql

i want to get current and current - 7 week id in sql server.
So far i can get that, but for week id under 10 is a problem for me.
DECLARE #CurrentWeek nvarchar(6),#CurrentWeek7 nvarchar(6)
SET #CurrentWeek = CAST(datepart(yy, GETDATE()) AS CHAR(4))+''+CAST(datepart(ww, GETDATE()) AS CHAR(2))
SET #CurrentWeek7 = CAST(datepart(yy, DATEADD(WEEK, -7, GETDATE())) AS CHAR(4)) +''+CAST(datepart(ww, DATEADD(WEEK, -7, GETDATE())) AS CHAR(2))
Problem is that i get for example calendar week id without 0 between year and week number for week number under 10.
20199 instead of 201909. I want this to work also for week number bigger than 10, for example 201911
You can use the RIGHT trick to force a left-sided 0 when the week day is 9 or less.
DECLARE
#CurrentWeek nvarchar(6),
#CurrentWeek7 nvarchar(6)
DECLARE #TodayLastWeek DATE = DATEADD(DAY, -7, GETDATE())
SET #CurrentWeek = CONVERT(VARCHAR(4), DATEPART(YEAR, GETDATE()))
+ RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(WEEK, GETDATE())), 2)
SET #CurrentWeek7 = CONVERT(VARCHAR(4), DATEPART(YEAR, #TodayLastWeek))
+ RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(WEEK, #TodayLastWeek)), 2)
SELECT
CurrentWeek = #CurrentWeek,
CurrentWeek7 = #CurrentWeek7
Result:
CurrentWeek CurrentWeek7
201909 201908
PD: Please check Panagiotis' comment, his solution is faster and simpler.
I am thinking of logic like this:
DECLARE #CurrentWeek nvarchar(6),
#CurrentWeek7 nvarchar(6);
SET #CurrentWeek = dateadd(day,
1 - datepart(weekday, getdate()),
convert(date, getdate())
);
SET #CurrentWeek7 = dateadd(week, -7, #CurrentWeek);
The key idea is that the historical week should be based on the definition of the current week.
DECLARE #CurrentWeek nvarchar(6),#CurrentWeek7 nvarchar(6)
SET #CurrentWeek = CAST(datepart(yy, GETDATE()) AS CHAR(4))* 100+''+CAST(datepart(ww, GETDATE()) AS CHAR(2))
SET #CurrentWeek7 = CAST(datepart(yy, DATEADD(WEEK, -7, GETDATE())) AS CHAR(4))* 100 +''+CAST(datepart(ww, DATEADD(WEEK, -7, GETDATE())) AS CHAR(2))

SQL - Run second Query if count result = 0

Both my SELECT queries work below and return values with as two separate results. What I would like to do is if the first SELECT statement returns a 0 and it will sometimes due to the nature of our work, I would like the second to run ignoring the first one that returns zero if possible. IF the first one returns a result greater than zero then I do not want the second to run.
I have been all over looking and tried different IF ELSE and such but because of the specific date/time formulas used I am thinking it may not be possible or I this may have to be re-written altogether. There is a purpose for this but I will not bore you. Thanks in advance!
Declare #StartDate as DateTime
Declare #EndDate as DateTime
Declare #TodaysDate as DateTime
Declare #Previous as DateTime
Declare #Previous2 as DateTime
set #TodaysDate = GETDATE()
set #Previous = DATEADD(day,-1,#TodaysDate)
set #Previous2 = DATEADD(day,-2,#TodaysDate)
-- SELECT Statetment one starts here
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous)) + '-' +
convert(varchar(2), datepart(dd, #Previous)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous)) + '-' +
convert(varchar(2), datepart(dd, #Previous)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
-- Query 2 Starts, Declarations already made at beginning
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
You can try to store the value of your first query result in a variable and then then check the value like
declare #myVar int
SELECT #myVar = Count(*) as FirstShfitPrevious
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate)
if(#myVar = 0)
//Here your second query logic
begin
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
end
use NOT Exists..
if NOT Exists
(Select 1 as FirstShfitPrevious--first query
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
)
Begin
SELECT Count(*) as FirstShfitPrevious2--second query
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
END
Else
Begin
--First query
End
or even that way:
SELECT TOP 1 Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
GROUP BY CAST(Close_Time_Stamp AS DATE)
ORDER BY CAST(Close_Time_Stamp AS DATE) DESC
with period covering both date ranges.

Sql Server select datetime without seconds

I have datetime column value below
2015-01-04 20:37:00.000
I tried below
cast(cast(MyDateColumn as date) as datetime)+cast(datepart(hour,MyDateColumn ) as float)/24
as MyDateColumn
and
CAST(CONVERT(CHAR(16),MyDateColumn,113) AS datetime) as MyDateColumn
These are did not work for me
How can i get above datetime as 01-04.2015 20:37 ?
Since MS SQL 2012, you can use FORMAT,
SELECT FORMAT([MyDateColumn], 'dd-MM.yyyy HH:mm')
In MYSQL it will work
SELECT DATE_FORMAT(date, '%Y-%m-%d %H:%i') AS formated_date FROM table;
In MS SQL It will work
SELECT FORMAT(getdate(), 'dd-mm-yyyy HH:mm')
In SQL Server this will work:
DECLARE #now [datetime];
SET #now = GETDATE();
SELECT
CONVERT([varchar](10), #now, 105) + ' ' +
RIGHT('0' + CONVERT([varchar](2), DATEPART(HOUR, #now)), 2) + ':' +
RIGHT('0' + CONVERT([varchar](2), DATEPART(MINUTE, #now)), 2);
In SQL Server this should do the trick:
declare #dt datetime = '2015-01-04 20:37:00.000'
select right('0' + cast(DATEPART(MM, #dt) as varchar), 2) + '-'
+ right('0' +cast(DATEPART(DAY, #dt) as varchar), 2) + '.'
+ cast(DATEPART(YEAR, #dt) as varchar) + ' '
+ right('0' +cast(DATEPART(HOUR, #dt) as varchar), 2) + ':'
+ right('0' +cast(DATEPART(MINUTE, #dt) as varchar), 2)
Simply,
SELECT CAST(CONVERT(varchar, GETDATE(), 100) as datetime)
Here's another way and you get a datetime in return.
SELECT DATEADD(
MILLISECOND,
DATEPART(MILLISECOND, '2016-02-16 13:45:24.573') * -1,
DATEADD(SECOND, DATEPART(SECOND,'2016-02-16 13:45:24.573') * -1,
'2016-02-16 13:45:24.573')
)
this is the way i do it. I needed to get -2 minutes
select CONVERT(datetime, CONVERT(CHAR(18), DATEADD(minute, -2, getdate()) , 113) + '00')
Format(Cast(Convert(varchar(15),Cast(timeval as Time),100) as DateTime),'hh:mm tt') As newtime
This will remove seconds from time as well as add AM,PM with time.

Subtracting One Year

SELECT
#begindate = dateadd(mm,-1,CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/15/' + CAST(datepart(YYYY,getdate() -1) AS varchar(4))),
#enddate = CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/14/' + CAST(datepart(YYYY,getdate() -1) AS varchar(4))
Right now this code returns the dates May 15th - June 14th. Those are the required dates that I need, but what I also need is for it to be in the year 2013, and this returns the year 2014. I've tried doing a dateadd(yyyy, -1) and it didn't work. So I was wondering if anyone knew how I would be able to get last years date.
If DateAdd didn't work, there must have been an error in your implementation. Try it like this after your existing code:
SET #begindate = dateadd(year, -1, #begindate);
SET #enddate = dateadd(year, -1, #enddate)
declare #begindate datetime
declare #enddate datetime
set #begindate = dateadd(mm,-1,CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/15/' + CAST(datepart(YYYY, getdate()) - 1 AS varchar(4)))
set #enddate = CAST(datepart(mm,getdate() ) AS VARCHAR(2)) + '/14/' + CAST(datepart(YYYY, getdate()) - 1 AS varchar(4))
select #begindate
union all
select #enddate
Instead of working with strings you can use date variables and date arithmetic:
declare #lastyear date=dateadd(yy,-1,cast(getdate() as date))
declare #currentMonth date=dateadd(d,-day(#lastyear),#lastyear)
declare #prevMonth date=dateadd(m,-1,#currentMonth)
select #lastyear,DATEADD(d,14,#currentMonth),DATEADD(d,15,#prevMonth)
In SQL Server 2012 it's even easier because you can use the DATEFROMPARTS function to construct a new date from its parts.