Creating function error sql server 2008 - sql-server-2008

I want to create a fucntion, but getting error.
below is query:
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS TABLE
AS BEGIN
DECLARE
#TIMER_START_ACTIVITY_ID INT,
#TIMER_START_ACTIVITY_COMPLETED_ON DATETIME,
#TIMER_END_ACTIVITY_ID INT,
#TIMER_END_ACTIVITY_COMPLETED_ON DATETIME,
#SLA_TIME_SCHEDULE_IN_DAYS INT,
#SLA_DISPLAY VARCHAR(20),
#START_DATE DATETIME,
#END_DATE DATETIME,
#BUSINESS_START_TIME VARCHAR(10),
#BUSINESS_END_TIME VARCHAR(10),
#BUSINESS_HOURS INT,
#SLA_CUT_OFF_TIME VARCHAR(10),
#IS_OBJECT_STATUS_IS_TERMINAL INT,
#COMPLETED_ACTION_ID INT,
#UNCHECKED_ACTION_ID INT,
#DAY_ADDED INT
SELECT #IS_OBJECT_STATUS_IS_TERMINAL = CASE when wos.FLG_STATUS_TYPE = 'W' THEN 0 ELSE 1 END
FROM WF.WF_OBJECT_INSTANCE woi
INNER JOIN WF.WF_OBJECT_STATUS wos ON wos.OBJECT_STATUS_ID = woi.OBJECT_STATUS_ID
WHERE woi.LINK_PK_ID = #OBJECT_PK_ID
SET #SLA_TIME_SCHEDULE_IN_DAYS = (SELECT CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN lr.RUSH_NO_OF_DAYS ELSE s.NUM_OF_DAYS END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #SLA_DISPLAY = (SELECT
CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN s.DISPLAY_NAME + ' (' + CAST(lr.RUSH_NO_OF_DAYS AS VARCHAR) + ')' ELSE s.DISPLAY_NAME END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #BUSINESS_START_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_START_TIME')
SET #BUSINESS_END_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_END_TIME')
SET #BUSINESS_HOURS = (SELECT CAST(DATEDIFF(hour, CAST(#BUSINESS_START_TIME AS DATETIME), CAST(#BUSINESS_END_TIME AS DATETIME)) AS INT))
SET #SLA_CUT_OFF_TIME = (SELECT DATEPART(hour, CAST(s.CONFIG_VALUE AS TIME)) FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'SLA_CUT_OFF_TIME')
SET #COMPLETED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_COMPLETED')
SET #UNCHECKED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_UNCHECKED')
--GET SLA TIMER ACTIVITY IDs
SELECT #TIMER_START_ACTIVITY_ID = t.START_ACTIVITY_ID,
#TIMER_END_ACTIVITY_ID = t.END_ACTIVITY_ID
FROM [WF].WF_TIMER t
WHERE t.NAME = 'SLA_TIMER'
--Get START ACTIVITY ON
SELECT #TIMER_START_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
--AND
----{
--0 = ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
-- FROM WF.WF_OBJECT_ACTIVITY_HISTORY
-- WHERE LINK_PK_ID = #OBJECT_PK_ID
-- AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
-- AND ACTION_ID = #COMPLETED_ACTION_ID
-- ORDER BY ACTION_ON DESC), 0)
----}
ORDER BY ACTION_ON DESC
--Get END ACTIVITY ON
SELECT #TIMER_END_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
ORDER BY ACTION_ON DESC
--TO DO
--SET #TIMER_START_ACTIVITY_COMPLETED_ON = '2014-05-15 02:40:21.100'
--SET #TIMER_END_ACTIVITY_COMPLETED_ON = '2014-05-14 12:40:21.100'
SET #START_DATE = #TIMER_START_ACTIVITY_COMPLETED_ON
SET #DAY_ADDED = #SLA_TIME_SCHEDULE_IN_DAYS -- SLA Schedule Days
+ CASE WHEN DATEPART(hour, #TIMER_START_ACTIVITY_COMPLETED_ON) >= #SLA_CUT_OFF_TIME THEN 0 ELSE -1 END -- SLA Cut Off Time
SET #END_DATE = #START_DATE + #DAY_ADDED
--Exclud Holidays
--{
DECLARE #START_ON_DATE DATETIME = CAST(#START_DATE AS DATE)
WHILE #DAY_ADDED > 0
BEGIN
SELECT #END_DATE = #START_ON_DATE + #DAY_ADDED
--COUNT NO OF HOLIDAYS IF FALLING WITHIN START-DATE AND END-DATE
SELECT #DAY_ADDED = COUNT(*) FROM [WF].WF_CALENDAR WC --HOLIDAY LIST
WHERE WC.DATE BETWEEN #START_ON_DATE+1 AND #END_DATE AND (WC.IS_WEEKEND = 1 OR WC.IS_HOLIDAY = 1)
SET #START_ON_DATE = #END_DATE
END
--}
SET #END_DATE = (CAST(CAST(CAST(#END_DATE AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME))
;WITH TIMER_CTE AS (
SELECT #START_DATE AS OBJECT_CREATED_ON,
#END_DATE AS OBJECT_END_ON,
DIFFERENCE_IN_DAYS = DATEDIFF(dd, GETDATE(), #END_DATE),
TODAY_REMAINING_MINUTES =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))
ELSE 0 END,
TODAY_REMAINING_HOURS =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN (DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))/60)
ELSE 0 END
)
RETURN (
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY,
SLA_DUE = CONVERT(VARCHAR(10), CONVERT(DATETIME, tc.OBJECT_END_ON, 1), 101),
#BUSINESS_END_TIME AS BUSINESS_END_TIME,
SLA_START_ACTIVITY_CHECKED_ON = tc.OBJECT_CREATED_ON,
SLA_END_ACTIVITY_CHECKED_ON = #TIMER_END_ACTIVITY_COMPLETED_ON,
SLA_MISSED = CASE WHEN
--TODAY_REMAINING_MINUTES <= 0
--AND CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
--OR
( GETDATE()> #END_DATE)
OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 'Missed' ELSE NULL END,
tc.TODAY_REMAINING_HOURS,
tc.TODAY_REMAINING_MINUTES,
LAST_DAY_TIME_REMAINING =
CASE
WHEN #TIMER_END_ACTIVITY_COMPLETED_ON <= #END_DATE THEN 'Successful Completed'
WHEN CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
THEN
CASE WHEN
tc.TODAY_REMAINING_HOURS <=0 AND tc.TODAY_REMAINING_MINUTES > 0 THEN
CASE WHEN tc.TODAY_REMAINING_MINUTES = 1 THEN CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' min remaining'
ELSE CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' mins remaining' END
WHEN tc.TODAY_REMAINING_HOURS =1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hour remaining'
WHEN tc.TODAY_REMAINING_HOURS >1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hours remaining'
ELSE NULL
END
ELSE NULL
END,
REMAINING_DAYS = CASE WHEN tc.DIFFERENCE_IN_DAYS <=0 THEN '0 day'
WHEN tc.DIFFERENCE_IN_DAYS > 1 THEN CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' days '
ELSE CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' day ' END
FROM TIMER_CTE tc
)
END;
GO
I am getting this error:
Msg 156, Level 15, State 1, Procedure WFSlaTimer, Line 144
Incorrect syntax near the keyword 'RETURN'.
Msg 178, Level 15, State 1, Procedure WFSlaTimer, Line 144
A RETURN statement with a return value cannot be used in this context.
Msg 102, Level 15, State 31, Procedure WFSlaTimer, Line 189
Incorrect syntax near 'BEGIN'.
Any help please

There are two kind of function that return table. the inline function and multi-statement function. Yours is multi-statement. Here is the syntax for this:
--Transact-SQL Multistatement Table-valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name
( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ = default ] [READONLY] }
[ ,...n ]
]
)
RETURNS #return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[ ; ]
For more information refer to CREATE FUNCTION (Transact-SQL) BOL documentation.

You have to define the returned table's structure (fields and data types)
1) Add a variable name to the function definition (#tableVariable in the above example).
2) Fill the table definition (columns and datatypes)
3) Modify your function to insert the result into the defined table variable, then use an empty RETURN statement when the function should return.
1st step
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS #tableVariable TABLE (
IS_SHOW_SLA INT,
StartDate DATETIME2,
EndDate DATETIME2
/** List all of your returned columns like when you creating a table **/
)
AS
BEGIN
/** Do your stuff **/
INSERT INTO #tableVariable ( /* field list */) VALUES (/* value list */)
-- OR --
INSERT INTO #tableVariable ( /* field list */)
SELECT /* FieldList */ FROM myCTE
RETURN
END
2nd step
Modify your RETURN () statement like this:
INSERT INTO #tableVanriable (IS_SHOW_SLA , StartDate , EndDate)
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY
/** .... **/
FROM TIMER_CTE tc
/** 3rd step **/
RETURN

Related

Linq to SQL generates much slower query

I've got a SQL query that when I run it in SQL Server Mgmt Studio takes 15 seconds to complete. When I translate it to linq and run it in LINQPad it takes 1:50 to complete. Have I just completely bungled the "translation" to linq?
This is the SQL:
WITH details AS (
SELECT DISTINCT SerialNumber, OrgLevel3, OrgLevel4, [Status Label]
FROM vw_PSM_AssetIntransit
WHERE yyyyww = DATENAME(yy, GETDATE()) + RIGHT('00' + DATENAME(wk, GETDATE()), 2) AND pro_status <> 'retired'
)
SELECT OrgLevel3, OrgLevel4, COUNT(DISTINCT SerialNumber) Total,
SUM(CASE WHEN [Status Label] NOT IN ('15-21 Days InTransit', '8-14 Days InTransit', 'over 21 Days InTransit') THEN 1 ELSE 0 END) Compliant
FROM details
GROUP BY OrgLevel3, OrgLevel4
ORDER BY 1, 2
and this is the LINQ I translated it to:
var now = DateTime.Now;
var dtf = System.Globalization.DateTimeFormatInfo.CurrentInfo;
var calendar = dtf.Calendar;
var yearWW = now.Year * 100 + calendar.GetWeekOfYear(now, dtf.CalendarWeekRule, dtf.FirstDayOfWeek);
var badStatusLabels = new string[] { "15-21 Days InTransit", "8-14 Days InTransit", "over 21 Days InTransit" };
var details = (
from r in Vw_PSM_AssetIntransit
where r.yyyyww == yearWW && r.Pro_status != "retired"
select new { r.SerialNumber, r.OrgLevel3, r.OrgLevel4, r.StatusLabel }
).Distinct();
var data = from r in details
group r by new { r.OrgLevel3, r.OrgLevel4 } into grp
orderby grp.Key.OrgLevel3, grp.Key.OrgLevel4
select new
{
OrgLevel3 = grp.Key.OrgLevel3,
OrgLevel4 = grp.Key.OrgLevel4,
Total = grp.Select(x => x.SerialNumber).Distinct().Count(),
Compliant = grp.Sum(x => !badStatusLabels.Contains(x.StatusLabel) ? 1 : 0)
};
Console.WriteLine(data);
This is what LINQPad shows the SQL query came out as:
-- Region Parameters
DECLARE #p0 Int = 201816
DECLARE #p1 NVarChar(1000) = 'retired'
DECLARE #p2 NVarChar(1000) = '15-21 Days InTransit'
DECLARE #p3 NVarChar(1000) = '8-14 Days InTransit'
DECLARE #p4 NVarChar(1000) = 'over 21 Days InTransit'
DECLARE #p5 Int = 1
DECLARE #p6 Int = 0
-- EndRegion
SELECT [t3].[OrgLevel3], [t3].[OrgLevel4], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t5].[SerialNumber]
FROM (
SELECT DISTINCT [t4].[SerialNumber], [t4].[OrgLevel3], [t4].[OrgLevel4], [t4].[Status Label]
FROM [vw_PSM_AssetIntransit] AS [t4]
WHERE ([t4].[yyyyww] = #p0) AND ([t4].[pro_status] <> #p1)
) AS [t5]
WHERE ((([t3].[OrgLevel3] IS NULL) AND ([t5].[OrgLevel3] IS NULL)) OR (([t3].[OrgLevel3] IS NOT NULL) AND ([t5].[OrgLevel3] IS NOT NULL) AND ((([t3].[OrgLevel3] IS NULL) AND ([t5].[OrgLevel3] IS NULL)) OR (([t3].[OrgLevel3] IS NOT NULL) AND ([t5].[OrgLevel3] IS NOT NULL) AND ([t3].[OrgLevel3] = [t5].[OrgLevel3]))))) AND ((([t3].[OrgLevel4] IS NULL) AND ([t5].[OrgLevel4] IS NULL)) OR (([t3].[OrgLevel4] IS NOT NULL) AND ([t5].[OrgLevel4] IS NOT NULL) AND ((([t3].[OrgLevel4] IS NULL) AND ([t5].[OrgLevel4] IS NULL)) OR (([t3].[OrgLevel4] IS NOT NULL) AND ([t5].[OrgLevel4] IS NOT NULL) AND ([t3].[OrgLevel4] = [t5].[OrgLevel4])))))
) AS [t6]
) AS [Total], [t3].[value] AS [Compliant]
FROM (
SELECT SUM([t2].[value]) AS [value], [t2].[OrgLevel3], [t2].[OrgLevel4]
FROM (
SELECT
(CASE
WHEN NOT ([t1].[Status Label] IN (#p2, #p3, #p4)) THEN #p5
ELSE #p6
END) AS [value], [t1].[OrgLevel3], [t1].[OrgLevel4]
FROM (
SELECT DISTINCT [t0].[SerialNumber], [t0].[OrgLevel3], [t0].[OrgLevel4], [t0].[Status Label]
FROM [vw_PSM_AssetIntransit] AS [t0]
WHERE ([t0].[yyyyww] = #p0) AND ([t0].[pro_status] <> #p1)
) AS [t1]
) AS [t2]
GROUP BY [t2].[OrgLevel3], [t2].[OrgLevel4]
) AS [t3]
ORDER BY [t3].[OrgLevel3], [t3].[OrgLevel4]

Sorting always returns the same result

I have the following query
Create procedure usp_GetBills
#PageNo INT = 1,
#PageSize INT = 10,
#SortOrder INT = 1,
#SortColumn VARCHAR(20) = ''
AS
BEGIN
DECLARE
#lSortColumn VARCHAR(20),
#lFirstRec INT,
#lLastRec INT
SET #SortColumn = LTRIM(RTRIM(#SortColumn))
SET #lFirstRec = (#PageNo - 1) *#PageSize
SET #lLastRec = (#PageNo * #PageSize + 1)
;WITH CTE_Results
AS(
SELECT ROW_NUMBER() OVER (ORDER BY(
#SortColumn))
AS ROWNUM,P.BillNo, P.PropertyNo, P.BillDate, P.BillFromDate, P.BillToDate, P.BillAmount, P.DueDate, P.Status
FROM Bill P)
SELECT * from CTE_Results
WHERE ROWNUM > #lFirstRec
AND ROWNUM < #lLastRec
ORDER BY
--ROWNUM * #SortOrder
CASE WHEN #SortOrder = 1 THEN #SortColumn ELSE '' END ASC,
CASE WHEN #SortOrder = 2 THEN #SortColumn ELSE '' END DESC
END
And so if I exec
DECLARE #return_value int
EXEC #return_value = [dbo].[usp_GetBills]
#PageNo = 2,
#PageSize = 10,
#SortOrder = N'1',
#SortColumn = 'BillNo'
SELECT 'Return Value' = #return_value
This query gives me the same result always w.r.t SortOrder. The SortOrder doesn't seems to work properly. I referred this link
Thanks.
we cant pass dynamic columns in order by clause
So this
Create procedure usp_GetBills
#PageNo INT = 1,
#PageSize INT = 10,
#SortOrder INT = 1,
#SortColumn VARCHAR(20) = ''
AS
BEGIN
DECLARE
#lSortColumn VARCHAR(20),
#lFirstRec INT,
#lLastRec INT
SET #SortColumn = LTRIM(RTRIM(#SortColumn))
SET #lFirstRec = (#PageNo - 1) *#PageSize
SET #lLastRec = (#PageNo * #PageSize + 1)
;WITH CTE_Results
AS(
SELECT ROW_NUMBER() OVER (ORDER BY(
#SortColumn))
AS ROWNUM,P.BillNo, P.PropertyNo, P.BillDate, P.BillFromDate, P.BillToDate, P.BillAmount, P.DueDate, P.Status
FROM Bill P)
SELECT * from CTE_Results
WHERE ROWNUM > #lFirstRec
AND ROWNUM < #lLastRec
ORDER BY
--ROWNUM * #SortOrder
CASE WHEN #SortIndex = 1 THEN BillNo END ASC,
CASE WHEN #SortIndex = 2 THEN BillNo END DESC,
CASE WHEN #SortIndex = 1 THEN PropertyNo END ASC
CASE WHEN #SortIndex = 2 THEN PropertyNo END DESC
END

Struggling to get desired return

I'm relatively new to SQL, but am generally a quick learner and this particular query has stumped me for a few days. Any help would be beyond appreciated at this point.
When I run the below query, I only return rows where there exists a statusdatetime (the agent logged in that day). I need to return a row even when the agent didn't log in but was scheduled. How can I change this query to return a NULL for that. I thought the left join would work.
DECLARE #startDate datetime
DECLARE #endDate datetime
SET #startDate = GETDATE()
SET #endDate = GETDATE()
SET #startDate = CONVERT(DATETIME, CONVERT(varchar(11),#startDate, 111 ) + ' 00:00:00', 111)
SET #endDate = CONVERT(DATETIME, CONVERT(varchar(11),#endDate, 111 ) + ' 23:59:59', 111)
Begin
Create table #boris5table(
Firstname varchar(50),
lastname varchar (50),
username varchar (50),
starttime datetime,
loggedintime datetime,
variation int)
End
Insert into #boris5table (Firstname, lastname, username, starttime, loggedintime, variation)
Select firstname, lastname, userid,
(cast(DATEADD(MINUTE, (-300 +
(select min(startoffset) from [dbo].[IO_ScheduleInterval]
Where activitytypeid = '0000000000000000000004'
and PaidTime = '1'
and f1.agentid = f2.agentid
and ScheduleID = f1.scheduleid)), StartDateTimeUTC) as datetime)),
case when exists (select count(*), statusdatetime from [dbo].[AgentActivityLog] Where StatusDateTime between #startdate and #enddate Group by StatusDateTime) then min(statusdatetime)
Else NULL
End as LoggedInTime,
DATEDIFF(minute, (cast(DATEADD(MINUTE, (-300 +
(select min(startoffset) from [dbo].[IO_ScheduleInterval]
Where activitytypeid = '0000000000000000000004'
and PaidTime = '1'
and f1.agentid = f2.agentid
and ScheduleID = f1.scheduleid)), StartDateTimeUTC) as datetime)),
case when exists (select statusdatetime from [dbo].[AgentActivityLog] Where StatusDateTime between #startdate and #enddate and f3.UserId = f2.UserName) then min(statusdatetime)
Else 'NULL' END)
as 'Variation (minutes)'
From [I3_IC].[dbo].[IO_Schedule] as f1
left join [dbo].[IO_Agent] as f2 on f1.AgentID = f2.AgentID and (CAST(DATEADD(hour, - 5, f1.StartDateTimeUTC) as date)) between #startdate and #enddate
left join [dbo].[Individual] as f4 on f2.UserName = f4.WebLogin and LastName <> '-'
left join [dbo].[AgentActivityLog] as f3 on f2.UserName = f3.UserId and (CAST(DATEADD(hour, -1, f3.StatusDateTime) as date)) between #startdate and #enddate
Group by firstname, lastname, f2.UserName, ScheduleID, f1.AgentID, f2.AgentID, StartDateTimeUTC, f3.UserId
Select *
From #boris5table
drop table #boris5table

getting a null error when using today's dates and yesterday's dates

I have run into a scenario that is giving me a null error and do not know how to fix it - can't even figure out where the null error is throwing.
CREATE PROCEDURE reportFreeCooling(
IN fromDate VARCHAR (50),
IN toDate VARCHAR (50),
IN timeZone VARCHAR (50)
)
BEGIN
DECLARE startDate VARCHAR (50);
DECLARE endDate VARCHAR (50);
DECLARE startDateOriginal VARCHAR (50);
DECLARE mylogID INT;
DECLARE myItemId varchar (50);
DECLARE myItemId2 varchar (50);
DECLARE xHours varchar (50);
DECLARE endHoursNull varchar(50);
DECLARE endHoursNotNull varchar (50);
DECLARE firstRow INT;
DECLARE firstRowDate varchar(50);
DECLARE minRowDate varchar (50);
DECLARE minRow int;
SET startDate = FROM_UNIXTIME(fromDate/1000);
SET endDate = FROM_UNIXTIME(toDate/1000);
SET startDateOriginal = FROM_UNIXTIME(fromDate/1000);
SET mylogID = (SELECT logID FROM logs WHERE details LIKE 'FCT%' LIMIT 1);
SET myItemID = (SELECT i.itemId FROM items i WHERE i.name LIKE '%KW PRE%');
SET myItemID2 = (SELECT i.itemId FROM items i WHERE i.name LIKE '%KW STA%');
DROP TABLE IF EXISTS tempTable3 CASCADE;
SET #sql = NULL;
SET #sql = CONCAT(
'CREATE TEMPORARY TABLE tempTable3 AS (SELECT
#row := #row + 1 AS rownum,
a.logId,a.name AS Type,
L1.recordId,
L2.recordId AS next_recordId,
L1.completed,
L2.completed AS next_completed,
L3.completed AS first_completed,
L1.activityId AS activityJoin,
L2.activityId AS next_activityId,
IF(L1.activityId = L2.activityId, 1, NULL) AS isError,
CASE
when a.name LIKE ''%Enable%'' THEN time_to_sec(timediff(L2.completed, L1.completed)) / 3600
ELSE NULL
END AS coolingHours,
TO_SECONDS(L2.completed) - TO_SECONDS(L1.completed) AS timeInSeconds,
((SUBSTR(l.details, INSTR(l.details, '':'') + 1))) AS charge,
time_to_sec(timediff(''', endDate, ''', ''', startDate, ''')) / 3600 AS totalTimeRange,
CONVERT_TZ(''', startDate, ''', ''UTC'', ''', timeZone, ''') AS startingDate,
CONVERT_TZ(''', endDate, ''', ''UTC'', ''', timeZone, ''') AS endingDate,
(L1.item', myItemID, ' - L1.item', myItemID2, ') AS itemDifference,
((L1.item', myItemID, ' - L1.item', myItemID2, ') *
(TIME_TO_SEC(TIMEDIFF(L2.completed, L1.completed))/3600)) AS kwDifference,
((L1.item', myItemID, ' - L1.item', myItemID2, ') * (SUBSTR(l.details, INSTR(l.details, '':'') + 1))) AS cost,
((((L1.item', myItemID, ' - L1.item', myItemID2, ') * (SUBSTR(l.details, INSTR(l.details,'':'') + 1)))
* (TIME_TO_SEC(TIMEDIFF(L2.completed, L1.completed)) / 3600))) AS costT,
DATABASE() AS databaseName, i.itemId ,l.details
FROM
(SELECT #row:=0)R,
(SELECT T1.completed
, (SELECT MIN(T2.completed)
FROM log',mylogID, ' T2
WHERE T2.completed > T1.completed) AS next_completed
, (SELECT MAX(T2.completed)
FROM log',mylogID, ' T2
WHERE T2.completed < T1.completed) AS frst_completed
FROM log',mylogID, ' T1
ORDER BY T1.completed
)TimeOrder
LEFT JOIN log', mylogID, ' L1 ON (L1.completed = TimeOrder.completed)
LEFT JOIN log', mylogID, ' L2 ON (L2.completed = TimeOrder.next_completed)
LEFT JOIN log', mylogID, ' L3 ON (L3.completed = TimeOrder.frst_completed)
LEFT JOIN activities a ON L1.activityId = a.activityId
LEFT JOIN logs l ON a.logId = l.logId
LEFT JOIN items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%''
)order by L1.completed');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
/* sets next row hours when date is after startdate and first is null */
SET #startDate = (SELECT MIN(completed) FROM tempTable3 WHERE coolingHours is NULL AND
completed BETWEEN startDate AND endDate);
SET #startDate2 = (SELECT MAX(completed) FROM tempTable3 WHERE completed < #startDate);
SET startDate = #startDate2;
/* sets end hours when last row is enabled and next_completed is greater than end date */
SET #endHoursNotNull = (SELECT MAX(completed) AS maxCompletedDateAndCoolingHoursNotNull FROM tempTable3 WHERE coolingHours is NOT NULL AND
completed BETWEEN startDate AND endDate);
SET endHoursNotNull= #endHoursNotNull;
SET #endHoursNull = (SELECT MAX(completed) AS maxCompletedAndCoolingHoursNull FROM tempTable3 WHERE coolingHours is NULL AND
completed BETWEEN startDate AND endDate);
SET endHoursNull = #endHoursNull;
/* sets first row hours when date is after startdate and first enabled */
SET firstRowDate = (SELECT MIN(completed) FROM tempTable3);
IF firstRowDate > startDateOriginal THEN SET startDateOriginal = firstRowDate; END IF;
SET #newcoolingHours = (SELECT (time_to_sec(timediff(next_completed, startDateOriginal)) / 3600) AS newCoolingHours
FROM tempTable3 WHERE completed >= startDateOriginal
AND completed BETWEEN startDate AND endDate LIMIT 1);
SET xHours = #newCoolingHours;
SET minRowDate = (SELECT MIN(completed) FROM tempTable3 WHERE completed BETWEEN startDate AND endDate LIMIT 1 );
SET minRow = (SELECT MIN(rowNum)FROM tempTable3 WHERE completed BETWEEN startDate AND endDate LIMIT 1 );
/* set first row number and hours for when first row in log(itemId) is greater then startdate */
SET #sqlTemp = NULL;
SET #sqlTemp =
CONCAT(
'SELECT rowNum,l.completed,l.next_completed,l.first_completed,startingDate,endingDate,Type,itemDifference,
''',startDateOriginal,''' AS oStartDate, ''',startDate,''' as startDate,
(time_to_sec(timediff(next_completed, completed)) / 3600)AS cHours,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN (time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600)
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN ''',xHours,'''
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN ((time_to_sec(timediff(''',endDate,''', completed))) / 3600)
ELSE coolingHours
END AS coolingHours,
isError,charge,totalTimeRange,
l.logId,databaseName,i.name,l.itemId,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN (itemDifference*(time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600))
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN (''',xHours,'''* itemDifference)
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN (itemDifference*((time_to_sec(timediff(''',endDate,''', completed))) / 3600))
ELSE kwDifference
END AS kwDifference,cost,
CASE
WHEN (''',startDateOriginal,''' > ''',startDate,''' AND Type LIKE ''%Enable%'' AND rowNum = ''',minRow,''')
THEN ((time_to_sec(timediff(next_completed, ''',startDateOriginal,''')) / 3600)* cost)
WHEN (DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,'''))
THEN (''',xHours,''' * cost)
WHEN (''',endHoursNotNull,''' > ''',endHoursNull,''' AND next_completed > ''',endDate,''' )
THEN (((time_to_sec(timediff(''',endDate,''', completed))) / 3600) * cost)
ELSE costT
END AS costT,l.details,timeInSeconds
FROM tempTable3 l
inner join items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%''
WHERE l.itemId = ''',myItemId,'''
AND completed BETWEEN ''', startDate, ''' AND ''', endDate, '''
');
PREPARE stmtTemp FROM #sqlTemp;
EXECUTE stmtTemp;
DEALLOCATE PREPARE stmtTemp;
DROP TEMPORARY TABLE tempTable3;
END //
DELIMITER ;
I do know that is has to do with the last row of data and the next_completed being null
last rows of data
row Num completed next_completed first_completed starting Date ending Date
28 12/28/2013 6:30:35 PM 12/29/2013 12:07:19 AM 12/27/2013 11:22:54 PM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
29 12/29/2013 12:07:19 AM 12/29/2013 8:56:58 AM 12/28/2013 6:30:35 PM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
30 12/29/2013 8:56:58 AM 12/31/2013 11:27:40 PM 12/29/2013 12:07:19 AM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM
31 12/31/2013 11:27:40 PM (null) 12/29/2013 8:56:58 AM 12/31/1969 10:00:00 PM 12/31/2013 10:00:00 PM

Syntax issue with BEGIN ... SET ... END

I have written the following stored procedure that uses a Date Dimension table to calculate the next occurrence of a date given a begin date and a frequency.
I am getting some odd syntax errors that seem to occur whenever I have an IF BEGIN SET IF SET END sequence.
In order to help debug, I have gone back in and added unneeded BEGIN and END statements around the one line IF statements.
Am I missing some type of BEGIN - END or IF - ELSE matching rule here? (I've marked the lines that the parser is complaining about with comments.)
CREATE PROCEDURE dbo.GetNextScheduledBusinessDayOccurance
(
#BeginDate DATE,
#Frequency CHAR(1)
)
AS
BEGIN
DECLARE #Date DATETIME,
#currentDate DATE,
#weekOfYear INT,
#dayOfWeek varchar(9),
#weekOfMonth tinyint,
#month varchar(2),
#dayOfQuarter tinyint,
#currentDayOfQuarter tinyint,
#quarterOfNextOccurance tinyint,
#yearOfNextOccurance int;
SET #currentDate = CONVERT(Date, GETDATE())
IF (#BeginDate > #currentDate)-- If it hasn't started yet
BEGIN
SET #Date = (SELECT TOP(1) [DATE] FROM dbo.dim_Date WHERE [DATE] >= #BeginDate AND [Date] > #currentDate AND (IsBusinessDay = 1) ORDER BY [DATE])
END
ELSE
BEGIN
IF #Frequency = 'A' --Annually
BEGIN
SET #Date = (SELECT TOP(1) [DATE] FROM dbo.dim_Date WHERE ([DATE] > #currentDate AND [Month] >= DATEPART(MONTH, #BeginDate) AND [Day] >= DATEPART(DAY, #BeginDate) AND IsBusinessDay = 1) ORDER BY [Date])
END
ELSE IF #Frequency = 'B' --Biweekly
BEGIN
SET #weekOfYear = (SELECT WeekOfYear FROM dbo.dim_Date WHERE [Date] = #BeginDate)
SET #dayOfWeek = (SELECT [DayOfWeek] FROM Dbo.dim_Date WHERE [Date] >= #BeginDate AND IsBusinessDay = 1)
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE ([DATE] > #currentDate AND [WeekOfYear]%2 = #weekOfYear%2 AND [DayOfWeek] = #dayOfWeek AND IsBusinessDay = 1) ORDER BY [Date]))
END
ELSE IF #Frequency = 'D' --Daily
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE ([DATE] > #currentDate AND IsBusinessDay = 1) ORDER BY [Date]))
END
ELSE IF #Frequency = 'E' -- Semi-Monthly (twice each month) (assume the 15th and last day of month)
BEGIN
-- GET the next 15th or last day of month.
SET #Date = (SELECT TOP(1) [Date] FROM dim_Date WHERE [Date] > #currentDate AND (Day = '15' OR (DateAdd(day, -1, DateAdd( month, DateDiff(month , 0,[Date])+1 , 0)) = [Date])) ORDER BY [Date])
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] > #Date) AND IsBusinessDay = 1) ORDER BY [Date])
END --Parser ERROR: Incorrect syntax near the keyword 'END'.
END
ELSE IF #Frequency = 'I' --Bimonthly (Every other month)
BEGIN
SET #Month = (SELECT Month FROM dbo.dim_Date WHERE [Date] = #BeginDate)
SET #Date = (SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE ([Date] > #currentDate AND [Month]%2 = #Month%2 AND [Day] = DATEPART(day, #BeginDate)) ORDER BY [Date])
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] > #Date) AND IsBusinessDay = 1) ORDER BY [Date])
END --Parser ERROR: Incorrect syntax near the keyword 'END'.
END
ELSE IF #Frequency = 'L' --Last Business Day of the Month
BEGIN
SET #Date = (SELECT TOP(1) [Date] FROM dim_Date WHERE [Date] > '2013-03-20 00:00:00.000' AND (DateAdd(day, -1, DateAdd( month, DateDiff(month , 0,[Date])+1 , 0)) = [Date]) ORDER BY [Date])
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] < #Date) AND IsBusinessDay = 1) ORDER BY [Date] DESC))
END
END
ELSE IF #Frequency = 'M' -- Monthly
BEGIN
SET #Date = (SELECT TOP(1) [Date] FROM dim_Date WHERE [Date] > #currentDate AND (Day > DATEPART(day, #BeginDate)) ORDER BY [Date])
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] > #Date) AND IsBusinessDay = 1) ORDER BY [Date])
END--Parser ERROR: Incorrect syntax near the keyword 'END'.
END
ELSE
IF #Frequency = 'Q' --Quarterly
BEGIN
SET #dayOfQuarter = (Select DayOfQuarter FROM dim_Date WHERE [DATE] = #BeginDate)
SET #currentDayOfQuarter = (Select DayOfQuarter FROM dim_Date WHERE [DATE] = #currentDate)
SET #quarterOfNextOccurance = (SELECT [Quarter] FROM dbo.dim_Date WHERE [Date] = #currentDate)
SET #yearOfNextOccurance = (SELECT [Year] FROM dbo.dim_Date WHERE [Date] = #currentDate)
--SELECT #dayOfQuarter DOQ, #currentDayOfQuarter curDOQ, #quarterOfNextOccurance QofNext, #yearOfNextOccurance YofNext
IF (#currentDayOfQuarter >= #dayOfQuarter)
SET #quarterOfNextOccurance = #quarterOfNextOccurance + 1
SET #Date = '1900-01-01'
WHILE (#Date < #currentDate) --Loop through this just in case we're close to the end of the Quarter, and there's no more business days left
BEGIN
IF (#quarterOfNextOccurance > 4)
BEGIN
SET #quarterOfNextOccurance = #quarterOfNextOccurance%4
SET #yearOfNextOccurance = #yearOfNextOccurance + 1
END
--SELECT #quarterOfNextOccurance QofNext, #yearOfNextOccurance YofNext
--CREATE a temp table with all of the business dates from the target quarter in decending order.
SELECT * INTO ##temp FROM (SELECT TOP(92) [Date], MAX(DayOfQuarter) as DOQ FROM dim_Date WHERE (YEAR = #yearOfNextOccurance AND Quarter = #quarterOfNextOccurance AND IsBusinessDay = 1) Group By Date ORDER BY Date DESC) as foo
SET #Date = (SELECT TOP(1) DATE from ##temp WHERE DOQ <= #dayOfQuarter)
SET #quarterOfNextOccurance = #quarterOfNextOccurance + 1 -- Go ahead and incriment this just in case we start the WHILE over.
--SELECT * FROM ##temp
BEGIN TRY DROP TABLE ##temp END TRY BEGIN CATCH END CATCH
END
END
ELSE
IF #Frequency = 'S' --Semi-annually
BEGIN
SET #Date = #BeginDate
WHILE (#Date < #currentDate)
BEGIN
SET #Date = (SELECT [Date] FROM dbo.dim_Date WHERE [Date] = DATEADD(MONTH, 6, #Date))
END
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
BEGIN
SET #Date = ((SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] > #Date) AND IsBusinessDay = 1) ORDER BY [Date])
END--Parser ERROR: Incorrect syntax near the keyword 'END'.
END
ELSE
IF #Frequency = 'W' --Weekly
BEGIN
SET #dayOfWeek = (SELECT [DayOfWeek] FROM dbo.dim_Date WHERE [Date] = #BeginDate)
SET #Date = (SELECT TOP(1) [Date] FROM Dbo.dim_Date WHERE DayOfWeek = #dayOfWeek AND [DATE] < #currentDate ORDER BY [DATE] DESC)
--SELECT #Date DATE, #BeginDate BeginDate
WHILE ((#Date < #currentDate) OR (#Date < #BeginDate))
BEGIN
SET #Date = (SELECT [Date] FROM dbo.dim_Date WHERE [Date] = DATEADD(Week, 1, #Date))
--SELECT #Date DateInWHile
END
IF ((SELECT IsBusinessDay FROM dim_Date WHERE [Date] = #Date) = 0)
SET #Date = (SELECT TOP(1) [Date] FROM dbo.dim_Date WHERE (([DATE] > #Date) AND IsBusinessDay = 1) ORDER BY [Date])
--SELECT #Date
END
ELSE
SET #Date = NULL
END
RETURN #Date
END
GO
You're missing a closing ):
BEGIN
SET #Date = ((
SELECT TOP(1) [Date]
FROM dbo.dim_Date
WHERE (([DATE] > #Date) AND IsBusinessDay = 1)
ORDER BY [Date]) ) -- Paren added here...
END --Parser ERROR: Incorrect syntax near the keyword 'END'.