Using DatePart in line of a larger sql clause - sql

This statement will correctly merge 2 columns ('DATE' and 'TIME'):
update AllBW1 set sUserTime =
CAST(
(
STR( YEAR( [DATE] ) ) + '/' +
STR( MONTH( [DATE] ) ) + '/' +
STR( DAY( [DATE] ) ) + ' ' +
(select DATENAME(hour, [TIME]))+ ':' +
(select DATENAME(minute, [TIME])) + ':' +
(select DATENAME(SECOND, [TIME]))
) as DATETIME)
where sUserTime is null
I'd like to refine the above so as to replace the default timezone with my own (GMT-6).
I've tried a few variations:
CAST((select DATEADD(hour, -6, DATENAME(hour, [TIME]))) as smalldatetime) + ':' +
and
(select CAST(DATEADD(hour, -6, DATENAME(hour, [TIME]))) as datetime) + ':' +
and have achieved no joy.
thx

The logfile as parsed into the SQL table by LogParser 2.2 has separate fields for Date and Time but, since both are formatted as datatime fields they end up looking like:
2012-01-04 00:00:00.000 for date (all time fields are zeroed)
2012-01-01 06:04:41.000 for time (all date field = first day of current year)
That's the reason the query is parsing each element the way it is. Thanks to Dems comment I simplified everything down. I've no doubt this can be optimized by for the volumes I'm dealing with this is adaquate:
update myTable set sUserTime =
(
DATENAME(YEAR, [DATE] ) + '/' +
DATENAME(MONTH, [DATE] ) + '/' +
DATENAME(DAY, [DATE] ) + ' ' +
DATENAME(hour, (dateadd(hh, -6, [time])))+ ':' +
DATENAME(minute, [TIME]) + ':' +
DATENAME(SECOND, [TIME])
)
where sUserTime is null

Related

Employee Total Experience SQL query

I have table with employees work experience. I want to get summary experience in format like yy mm dd.
e_id work_from work_to
2 2003-10-13 2004-02-12
2 2004-02-16 2004-06-30
2 2004-07-01 2006-01-31
2 2006-02-01 2017-07-12
Result should be: 13Y 8M 27D
Query like:
sum(datediff(month,work_from,work_to))/12,
sum(datediff(month,work_from,work_to)%12
works fine, but what about days?
Please note, the following query is a general summation which does not include leap years and the months are averaged between 365/12 in days since the amount of days in each month vary. If you want an exact figure that includes the exact amount of days, the algorithm will be more involved, but hopefully this gets you in a reasonably close ballpark figure.
SELECT CONVERT(VARCHAR(10), sum(datediff(year,work_from,work_to))-1) + 'Y' AS Years,
CONVERT(VARCHAR(10), FLOOR((sum(datediff(day, work_from,work_to)) - ((sum(datediff(year,work_from,work_to)) - 1) * 365)) / 30.4166)) + 'M' AS Months,
CONVERT(VARCHAR(10), CEILING(sum(datediff(day, work_from,work_to)) - ((sum(datediff(year,work_from,work_to)) - 1) * 365) - (FLOOR((sum(datediff(day, work_from,work_to)) - ((sum(datediff(year,work_from,work_to)) - 1) * 365)) / 30.4166) * 30.4166))) + 'D' AS Days,
CONVERT(VARCHAR(10), sum(datediff(day,work_from,work_to))) AS Total_Days
Here is my solution. This is the closest I can get. The problem that I had is that I cant escape the M after month.
DECLARE #SumExp Datetime = (SELECT CONCAT(
DATENAME(day, (SELECT SUM(DATEDIFF(day, WorkFrom, WorkTo))
FROM EmployeeWorkExperience)),
DATENAME(month, (SELECT SUM(DATEDIFF(day, WorkFrom, WorkTo))
FROM EmployeeWorkExperience)),
DATENAME(year, (SELECT SUM(DATEDIFF(day, WorkFrom, WorkTo))
FROM EmployeeWorkExperience))))
SELECT REPLACE(FORMAT(#SumExp, 'yyY MM# ddD'), '#', 'M')
DECLARE #work TABLE(
WorkId INT IDENTITY(1,1) PRIMARY KEY ,
work_from DATETIME NOT NULL,
work_to DATETIME NOT NULL )
INSERT INTO #work
( work_from, work_to )
VALUES ( '10/13/2003',
'2/12/2004'
),
(
'2/16/2004',
'6/30/2004'
),
('7/1/2004',
'1/31/2006'
),
('2/1/2006',
'7/12/2017'
)
DECLARE #seconds int
SELECT #seconds = SUM(DATEDIFF(SECOND, work_from, work_to))
FROM #work
DECLARE #VARDT DATETIME = DATEADD(SECOND, #seconds, 0)
SELECT CAST(DATEPART(YEAR, #VARDT) - 1900 AS VARCHAR(10)) + ' year(s) ' + CAST(DATEPART(MONTH, #VARDT) - 1 AS VARCHAR(2)) + ' month(s) '
+ CAST(DATEPART(DD, #VARDT) - 1 AS VARCHAR(2)) + ' day(s) ' + CAST(DATEPART(HOUR, #VARDT) AS VARCHAR(2)) + ' hour(s) '
+ CAST(DATEPART(MINUTE, #VARDT) AS VARCHAR(2)) + ' minute(s) ' + CAST(DATEPART(SECOND, #VARDT) AS VARCHAR(2)) + ' second(s)'

How to convert separated Year(int), Month(int) and Day(int) columns into DateTime

Our ERP system holds year, month and day in separate int columns. I want to combine those 3 int columns into one DateTime, How can I convert it in the SQL Server.
Year | Month | Day
--------------------
2016 | 1 | 23
You could use DATEFROMPARTS(SQL Server 2012+):
SELECT DATEFROMPARTS([Year], [Month], [Day]) AS DateTim
FROM table_name
SQL Server 2008 (assuming that year is 4-digit):
SELECT CAST(CAST([year] AS VARCHAR(4)) + '-' +
CAST([month] AS VARCHAR(2)) + '-' +
CAST([day] AS VARCHAR(2))
AS DATE) AS DateTim
FROM table_name;
LiveDemo
As Gordon Linoff proposed in comment to utilize YYYYMMDD as INT to convert to DATE:
SELECT CAST(CAST([year] * 10000 + [month]*100 + [day] AS VARCHAR(8))
AS DATE) AS DateTim
FROM table_name;
LiveDemo2
Addendum
To address ypercubeᵀᴹ concerns about dateformat we could utilize ISO-8601 which is not affected by DATEFORMAT or LANGUAGE settings:
yyyy-mm-ddThh:mm:ss[.mmm]
SELECT CAST(RIGHT('000'+ CAST([year] AS VARCHAR(4)),4) + '-' +
RIGHT('0' + CAST([month] AS VARCHAR(2)),2) + '-' +
RIGHT('0' + CAST([day] AS VARCHAR(2)),2) + 'T00:00:00' AS DATE)
FROM table_name
LiveDemo3
To handle years before 1000 should be padded with zeros.
We can use SQL's CONVERT function to get Datetime value :
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(2), Day) + '/' + CONVERT(VARCHAR(2), Month) + '/' + CONVERT(VARCHAR(4), Year),103) FROM Table_Name

Concatenating two TIME columns in SQL Server 2012

I want to concatenate two TIME columns and show as one column.
Example:
FromTime: 9:00
ToTime: 12:00
Result should be:
9:00-12:00
Generic SQL:
-- hh:mm:ss
SELECT 'result:' + CONVERT(CHAR(6), FromTime, 8) + '-' + CONVERT(CHAR(6), ToTime)
FROM yourTable
MySQL:
-- hh:mm
SELECT 'result:' + DATE_FORMAT(FromTime, '%H:%i') + '-' + DATE_FORMAT(ToTime, '%H:%i')
FROM yourTable
SQL Server:
-- hh:mm
SELECT 'result:' + convert(char(2), DATEPART(hh, FromTime)) + ':' +
CONVERT(CHAR(2), DATEPART(mm, FromTime)) + '-' +
CONVERT(CHAR(2), DATEPART(hh, ToTime)) + ':' +
CONVERT(CHAR(2), DATEPART(mm, ToTime))
FROM yourTable
declare #FromTime time
declare #ToTime time
set #FromTime='9:00'
set #ToTime='12:00'
select cast(#FromTime as varchar(10))+ '-' + cast(#ToTime as varchar(10)) as result
sql demo
You can use convert
select convert(VARCHAR(5),getdate(),108) + ' - ' + convert(VARCHAR(5),getdate()-1,108)

SQL Query - Have to determine if it is a specific day of the month (ex: 2 Tuesday of month)

I have an app that allows users schedule an action to occur in the future. For example, that can select a date and schedule it to run on that day every month (ex: the 15th of each month). However, I now need to allow them to select a week day and week of the month. For example, they need to run an action the first friday of the month. Therefore I am allowing the to select the weekday (monday, tuesday, wednesday....) and week of the month (1st, 2nd, 3rd, 4th or 5th).
Here is the query I currently use:
Declare #nowString varchar(19)
Declare #nowDateString varchar(19)
Declare #now datetime
Declare #lastMinute datetime
Declare #nowDate datetime
Set #nowString = '#currentDateTime#:00'
Set #nowDateString = LEFT(#nowString, 10)
set #now = #nowString
set #nowDate = DATEADD(dd, 0, DATEDIFF(dd, 0, #now))
set #lastMinute = DATEADD(mi, -1, #now)
select *
from message_prepared
where schedule = '1'
and active = '1'
and noaa = '0'
and (
(
schedule_type = 'recurring'
and startdate <= #nowDate
and isnull(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
and (
#nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #now
or #nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #lastMinute
)
-- Test for different type of recurring
and (
( ltrim(rtrim(recurring)) = 'M' and DATEPART(dd, startdate) = DATEPART(dd, #now) )
or ( ltrim(rtrim(recurring)) = 'W' and DATEPART(dw, startdate) = DATEPART(dw, #now) )
or ltrim(rtrim(recurring)) = 'D'
)
)
or (
schedule_type = 'once'
and startdate = #nowDate
and (
#nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #now
or #nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #lastMinute
)
)
)
and repeat_multiple_times = 0
UNION ALL
SELECT *
FROM MESSAGE_PREPARED
WHERE schedule = '1'
AND active = 1
AND noaa = 0
AND recurring = 'D'
AND repeat_multiple_times = 1
AND startDate IS NOT NULL
AND recurring_start_time_hour IS NOT NULL
AND recurring_start_time_hour < 24
AND recurring_start_time_min IS NOT NULL
AND recurring_start_time_min < 60
AND startdate <= #nowDate
AND ISNULL(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
AND
(
CASE WHEN repeat_unit = 'M'
THEN
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % repeat_interval
ELSE
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % (repeat_interval * 60)
END = 0
OR
CASE WHEN repeat_unit = 'M'
THEN
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % repeat_interval
ELSE
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % (repeat_interval * 60)
END = 0
)
This will only occur when reocurring is set to "M" and I would like to determine if today is the specific day of the week, week of the month and hour/min.
This is pretty simple logic. Today is the nth DOW of the month when the following is true:
Today is that day of the week
The day of the month is between 7*(n-1) + 1 and 7 * n
So, the first Monday of the month is always between the 1st and 7th, and so on. Here is an example case statement to test this:
declare #DayOfWeek varchar(255) = 'Thursday';
declare #Which int = 3;
select (case when datename(dw, Today) = #DayOfWeek and
(DAY(Today) - 1) / 7 = #Which - 1
then 1
else 0
end)
from (select CAST(getdate() as date) as Today) t
I've structured the query this way so you can test it with different values. Just replace the expression that defines Today, with something like getdate() - 3 or '2013-01-01'.

How to convert date into DD-MON-YYYY HH24:MI:SS format?

Can someone help me with SQL Date format?
The following statement
SELECT convert(VARCHAR(20),GETDATE(),113)
returns
04 Aug 2011 08:08:08.
I want the results like
Aug-04-2011 08:08:08
Thank you!
SELECT
LEFT(DATENAME(MONTH, Date), 3) + '-' +
RIGHT(100 + DAY(Date), 2) + '-' +
DATENAME(YEAR, Date) + ' ' +
CONVERT(varchar, Date, 108)
FROM (SELECT Date = GETDATE()) s
Off the top of my head, I think its:
SELECT convert(VARCHAR(20),GETDATE(),120)
EDIT:
This will work:
SELECT datename(day, GETDATE()) + '-'
+ substring(datename(month, GETDATE()),0,4) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
SECOND EDIT:
SELECT substring(datename(month, GETDATE()),0,4) + '-'
+ datename(day, GETDATE()) + '-'
+ datename(year, GETDATE()) + ' '
+ datename(hh, GETDATE()) + ':'
+ datename(mi, GETDATE()) + ':'
+ datename(ss, GETDATE())
THIRD EDIT:
select substring(datename(month, GETDATE()),0,4) + '-'
+ right(datename(day, GETDATE())+100,2) + '-'
+ datename(year, GETDATE()) + ' '
+ right(datename(hh, GETDATE())+100,2) + ':'
+ right(datename(mi, GETDATE())+100,2) + ':'
+ right(datename(ss, GETDATE())+100,2)
The built-in convert won't allow you to format your date exactly as you desire, unfortunately.
With a little manipulation, you can get there though:
SELECT stuff(stuff(convert(VARCHAR(20),GETDATE(),113), 3, 1, '-'), 7, 1, '-')
You could put this in a UDF and call that whenever you want your date formatted in this manner.