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]
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
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
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
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'.