Merge query in SQL Server stored procedure - sql

I'll admit I don't have a lot of DB experience as my last job had a DBA but this place has none. I have an existing MASSIVE stored procedure that I need to modify (I noticed a lot of duplication and cut that out).
Right now, it pulls so much data they used a cache table or the page crashes. They just want a smaller amount of data now for a separate page. I'm trying to edit this stored procedure and merge in my new query to it.
The existing stored procedure:
ALTER PROCEDURE [dbo].[PurchasingSupplyChainNeeds]
(#maxAgeInHours INT = 24)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sqlStmt NVARCHAR(max)
DECLARE #myName NVARCHAR(max) = Object_name(##PROCID)
DECLARE #needsRefresh INT
EXEC #needsRefresh = [cache].[NeedsRefresh]
#myName,
#maxAgeInHours
IF #needsRefresh = 1
BEGIN
DECLARE #CurrentMonth INT
DECLARE #DayOfWeek INT
DECLARE #EndOfWeekDate DATETIME
DECLARE #StartOfNextWeek DATETIME
DECLARE #WorkDaysInMonth INT
DECLARE #RunningDate DATE
DECLARE #WorkDaysLeftInMonth INT
DECLARE #DayOffset INT
SELECT #CurrentMonth = DATEPART(MONTH, GETDATE())
SELECT #DayOfWeek = DATEPART(WEEKDAY, GETDATE())
IF (#DayOfWeek = 1)
BEGIN
SET #StartOfNextWeek = GETDATE()
END
ELSE
BEGIN
SET #StartOfNextWeek = DATEADD(day, 8 - #DayOfWeek, GETDATE())
END
SELECT #DayOfWeek = DATEPART(weekday, GETDATE())
IF (#DayOfWeek = 7)
BEGIN
SET #EndOfWeekDate = Getdate()
END
ELSE
BEGIN
SET #EndOfWeekDate = DATEADD(day, -#DayOfWeek, GETDATE())
END
SET #WorkDaysInMonth = 0
SET #RunningDate = CONVERT(DATE, CONVERT(VARCHAR, #CurrentMonth) + '/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())))
WHILE ( Datepart(month, #RunningDate) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, #RunningDate)
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysInMonth = #WorkDaysInMonth + 1
END
SET #RunningDate = Dateadd(day, 1, #RunningDate)
END
SET #WorkDaysLeftInMonth = 0
SET #DayOffset = 0
WHILE ( Datepart(month, Dateadd(day, #DayOffset, Getdate())) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, Dateadd(day, #DayOffset, Getdate()))
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysLeftInMonth = #WorkDaysLeftInMonth + 1
END
SET #DayOffset = #DayOffset + 1
END;
WITH j
AS (SELECT Rtrim(Ltrim(imitmidx_sql.item_no)) AS ItemNo,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_1, ''))) AS ItemDescription1,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_2, ''))) AS ItemDescription2,
Rtrim(Ltrim(ISNULL(imitmidx_sql.activity_cd, '-'))) AS ActivityCode,
Rtrim(Ltrim(imitmidx_sql.pur_or_mfg)) AS PurchasedOrMfg,
Rtrim(Ltrim(ISNULL(imitmidx_sql.uom, '-'))) AS UOM,
/*
case statements ensure the price, avg_cost & price
are only observed from the item's primary location;
not secondary locations such as Amazon warehouses
*/
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN Rtrim(Ltrim(ISNULL(cicmpy.cmp_name, '')))
ELSE ''
END AS VendorName,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.avg_cost
ELSE 0
END AS AverageCost,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.price
ELSE 0
END AS Price,
iminvloc_sql.qty_on_hand AS QtyOnHand,
iminvloc_sql.qty_allocated AS QtyAllocated,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3IV') AS QtyIn3IV,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3TI') AS QtyIn3TI,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3FA') AS QtyIn3FA,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek1,
---Sales week 2 to 51 here
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek52,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear1,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear2,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYTD,
CASE
WHEN Datediff(week, imitmidx_sql.activity_dt, Getdate()) > 52 THEN 52
ELSE Datediff(week, imitmidx_sql.activity_dt, Getdate())
END AS ActiveWeeks,
(SELECT ( ISNULL(ForecastQty, 0) / #WorkDaysInMonth ) * #WorkDaysLeftInMonth
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS RemainingForecastQty,
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS ForecastQty1,
---ForecastQty 2 to 11
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Dateadd(month, 11, Getdate()))
AND [Year] = Datepart(year, Dateadd(month, 11, Getdate()))
AND Active = 1) AS ForecastQty12,
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty1,
---POQty 2 to 52
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty52
FROM imitmidx_sql imitmidx_sql WITH (NOLOCK)
LEFT OUTER JOIN iminvloc_sql iminvloc_sql WITH (NOLOCK)
ON imitmidx_sql.item_no = iminvloc_sql.item_no
AND
(
imitmidx_sql.loc = iminvloc_sql.loc /* Primary location for the item */
OR iminvloc_sql.loc = '3FA'/*Amazon Fullfillment Center*/
)
LEFT OUTER JOIN cicmpy cicmpy
ON iminvloc_sql.vend_no = cicmpy.cmp_code
AND cicmpy.cmp_type = 'S'),
i
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM],
Max([VendorName]) [VendorName],
Max([AverageCost]) [AverageCost],
Max([Price]) [Price],
Sum([QtyOnHand]) [QtyOnHand],
Sum([QtyAllocated]) [QtyAllocated],
Max([QtyIn3IV]) [QtyIn3IV],
Max([QtyIn3TI]) [QtyIn3TI],
Max([QtyIn3FA]) [QtyIn3FA],
Sum([SalesWeek1]) [SalesWeek1],
---SalesWeek2 to 51
Sum([SalesWeek52]) [SalesWeek52],
Sum([SalesYear1]) [SalesYear1],
Sum([SalesYear2]) [SalesYear2],
Sum([SalesYTD]) [SalesYTD],
Avg([ActiveWeeks]) [ActiveWeeks],
Avg([RemainingForecastQty]) [RemainingForecastQty],
Avg([ForecastQty1]) [ForecastQty1],
---ForecastQty2 to 11
Avg([ForecastQty12]) [ForecastQty12],
Avg([POQty1]) [POQty1],
---POQty2 to 51
Avg([POQty52]) [POQty52]
FROM j
WHERE [PurchasedOrMfg] = 'M'
GROUP BY [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM])
SELECT i.*,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 ) /
(
CASE
WHEN i.ActiveWeeks < 6 THEN i.ActiveWeeks
ELSE 6
END
)
END AS Last6WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 ) /
(
CASE
WHEN i.ActiveWeeks < 12 THEN i.ActiveWeeks
ELSE 12
END
)
END AS Last12WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 + i.SalesWeek40 + i.SalesWeek39 + i.SalesWeek38 + i.SalesWeek37 + i.SalesWeek36 + i.SalesWeek35 + i.SalesWeek34 + i.SalesWeek33 + i.SalesWeek32 + i.SalesWeek31 + i.SalesWeek30 + i.SalesWeek29 + i.SalesWeek28 + i.SalesWeek27 + i.SalesWeek26 + i.SalesWeek25 + i.SalesWeek24 + i.SalesWeek23 + i.SalesWeek22 + i.SalesWeek21 + i.SalesWeek20 + i.SalesWeek19 + i.SalesWeek18 + i.SalesWeek17 + i.SalesWeek16 + i.SalesWeek15 + i.SalesWeek14 + i.SalesWeek13 + i.SalesWeek12 + i.SalesWeek11 + i.SalesWeek10 + i.SalesWeek9 + i.SalesWeek8 + i.SalesWeek7 + i.SalesWeek6 + i.SalesWeek5 + i.SalesWeek4 + i.SalesWeek3 + i.SalesWeek2 + i.SalesWeek1 ) / i.ActiveWeeks
END AS Last52WeeksAvg,
( ISNULL(i.RemainingForecastQty, 0) + ISNULL(i.ForecastQty2, 0) + ISNULL(i.ForecastQty3, 0) + ISNULL(i.ForecastQty4, 0) + ISNULL(i.ForecastQty5, 0) + ISNULL(i.ForecastQty6, 0) + ISNULL(i.ForecastQty7, 0) + ISNULL(i.ForecastQty8, 0) + ISNULL(i.ForecastQty9, 0) + ISNULL(i.ForecastQty10, 0) + ISNULL(i.ForecastQty11, 0) + ISNULL(i.ForecastQty12, 0) ) / 52 AS AvgWeeklyForecast,
ISNULL(i.QtyIn3FA, 0) + ISNULL(i.QtyOnHand, 0) + ISNULL(i.QtyIn3TI, 0) - ISNULL(i.QtyAllocated, 0) AS QtyAvailable
INTO #outputToCache
FROM i
SET #sqlStmt = 'select * INTO [cache].[' + #myName + '] from #outputToCache'
EXEC sp_executesql
#sqlStmt
END
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
EXEC sp_executesql
#sqlStmt
END
My query:
SELECT
tb_1.SubPart AS 'Sub Part',
SUM(tb_1.FinalItemSubPartQuantity) 'Sub Part Quantity Needed',
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) 'Total Sales Week 1',
--- Total Sales Week 2 to 51 here
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek52) 'Total Sales Week 52'
FROM
[009Reports].[dbo].[ANC Parts] tb_1
JOIN
[555].[cache].[PurchasingSupplyChainNeeds] tb_2 ON tb_1.FinalPartNo = tb_2.ItemNo
GROUP BY
tb_1.SubPart
Replacing this query below with mine:
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
This is the error I get:
Msg 208, Level 16, State 1, Line 3168
Invalid object name 'i'
My query has 2 different tables in 2 different databases.

Currently, the stored procedure is using CTEs to create "temporary tables" based on (ugly and monstruous) queries and then use them to fill a table.
In general terms, a CTE is a table made from the results of a query, that's only usable by the immediate next query (this is: you create a CTE, then use it on a SELECT, INSERT, UPDATE... then the CTE gets destroyed).
What the SP is doing is this:
Creates CTE j using info and calculations from certain tables
Uses info from CTE j to create CTE i
Uses info from CTE i to create a temporary table #outputToCache
Dumps info from #outputToCache into a physical table cache.PurchasingSupplyChainNeeds
SELECTs and returns the info from cache.PurchasingSupplyChainNeeds as the resultset from the stored procedure
The error you're getting is because you're replacing the creation of CTE i with your own query, but i is still used later on to fill the temporary table.
Now, you say that what you are trying to achieve, is to retrieve a smaller amount of data from this last "cache" table for a separate page. IF I UNDERSTAND CORRECTLY (emphasized because I'm not 100% sure I got it already) you shouldn't modify this stored procedure (this is, add your query into it) because that would change the output of it, and would break anything that uses it. Not only that, your query is using info from the cache table, but the part you're trying to replace is what creates the CTE i that ultimately fills such table.
If what you really want to do is to change the resultset returned from this SP, then the query you need to replace with your own is the one that's assigned to the #sqlStmt variable at the end, so instead of
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
you would have
SET #sqlStmt = 'SELECT tb_1.SubPart AS [Sub Part], SUM(tb_1.FinalItemSubPartQuantity) [Sub Part Quantity Needed], SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) [Total Sales Week 1],...'
*Note the change of quoted aliases to square-bracketed ones
If your query is meant to return information for a separate page, you should create another stored procedure with your query and then call this new SP from this separate page. This is of course if this cache table doesn't get emptied/deleted by a different process later on. If this is the case, then you're into a world of pain, as you would either need to duplicate this existing SP almost in its entirety into your new SP and change the output as stated above; add an optional parameter that determines wich output should this SP return (e.g. if the parameter is 1 the output is the same as now, but if the parameter is 2 the output is your query); or change this existing stored procedure to not return a value and make other(s) to calls this one and return information as needed. Probably the last option is the "least ugly" one.

Related

Need query to start at the beginning of the month

SELECT DISTINCT
ATB.AcountCountDesc,
TB.LastFirstName,
N.EMAIL,
TB.AccountNumber,
TB.OpenShareCount,
TB.MemberOpenDate,
TB.OpenMemberCount,
TB.OpenShareBalance,
SH.ShareType,
FORMAT(SH.ShareOpenDate, 'MM/dd/yyyy') AS "ShareOpenDate",
SH.ShareCreatedByUser,
SH.ShareCreatedByUserName,
SH.ShareBranchName,
SH.ShareBranch,
cast(month(SH.ShareOpenDate) as varchar) + '/' + cast(year(SH.ShareOpenDate) as varchar) as 'Open Period',
CONCAT(SH.ShareCreatedByUser, '-',SH.ShareCreatedByUserName) 'Opened By'
FROM
arcu.vwARCUOperationMemberTrialBalance as TB
INNER JOIN arcu.vwARCUOperationMemberAccountTrialBalance as ATB ON TB.MemberSuppID = ATB.MemberID
and TB.ProcessDate = ATB.PDate
and TB.MemberStatus = 0 -- Account count for open Members only
and TB.AccountStatus <> 1
INNER JOIN arcu.vwARCUShare AS SH ON TB.ProcessDate = SH.ProcessDate
AND TB.AccountNumber = SH.AccountNumber
INNER JOIN NAME AS N ON TB.AccountNumber = N.PARENTACCOUNT
WHERE
ATB.AcountCountDesc = 1
AND TB.OpenShareCount >= 1
AND SH.ShareType = '00'
AND SH.ShareID != '40'
AND SH.ShareOpenDate >= DATEADD(s, 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), -2))
AND TB.MemberOpenDate = SH.ShareOpenDate
AND N.EMAIL <> ''
AND N.EMAIL is not null
order by MemberOpenDate Desc;
Issue: the MemberOpen Date starts on 08/02/2021.
Desired outcome: I need it to start on 08/01/2021
What I have tried: I have tried declaring a variable and calculating the start of the month by using datediff and still get the 08/02/2021 outcome.
I tried changing the => to = or <= and the issue persists. Please help.
You could calculate the 1st of the month using EOMONTH something like this
SELECT DISTINCT ATB.AcountCountDesc,TB.LastFirstName,N.EMAIL,TB.AccountNumber,TB.OpenShareCount,TB.MemberOpenDate,
TB.OpenMemberCount,TB.OpenShareBalance,SH.ShareType,FORMAT(SH.ShareOpenDate,'MM/dd/yyyy') AS "ShareOpenDate",
SH.ShareCreatedByUser,SH.ShareCreatedByUserName,SH.ShareBranchName,SH.ShareBranch,cast(month(SH.ShareOpenDate)
as varchar) + '/' + cast(year(SH.ShareOpenDate) as varchar)as 'Open Period', CONCAT(SH.ShareCreatedByUser,'-',SH.ShareCreatedByUserName)
'Opened By'
FROM arcu.vwARCUOperationMemberTrialBalance as TB
JOIN arcu.vwARCUOperationMemberAccountTrialBalance as ATB
ON TB.MemberSuppID = ATB.MemberID
and TB.ProcessDate = ATB.PDate
and TB.MemberStatus = 0 -- Account count for open Members only
and TB.AccountStatus <> 1
JOIN arcu.vwARCUShare AS SH
ON TB.ProcessDate = SH.ProcessDate
AND TB.AccountNumber = SH.AccountNumber
JOIN NAME AS N ON TB.AccountNumber = N.PARENTACCOUNT
WHERE
ATB.AcountCountDesc = 1 AND
TB.OpenShareCount >= 1 AND
SH.ShareType = '00' AND
SH.ShareID !='40' AND
SH.ShareOpenDate >= (select dateadd(day, 1, dateadd(month, -1, eomonth(getdate())))) AND
TB.MemberOpenDate = SH.ShareOpenDate AND
N.EMAIL <> '' AND
N.EMAIL is not null
order by MemberOpenDate Desc;

Returning LINE with no inner join match

I am trying to put a statement together the first part of the code works.
DECLARE #FYEND date, #YTD date, #PYTD date, #Openmonth date, #Monthtodatefrom date, #Monthtodateto date, #Priormonthdatefrom date, #Priormonthdateto date, #Currentmonth date
SET #FYEND = Dateadd(year,1,DATEADD(year,DATEDIFF(month,'19010701', getdate() ) /12,'19010701'))
SET #YTD = GETDATE()
SET #PYTD = DATEADD(YEAR,-1,#YTD)
SET #Openmonth = dateadd(DAY,1,dateadd(YEAR,-1,EOMONTH(#YTD,-1)))
SET #Monthtodatefrom = EOMONTH(getdate(),-2)
SET #Monthtodateto = Dateadd(DAY,1,eomonth(#ytd,-1))
SET #Priormonthdatefrom= DATEADD(YEAR,-1,#monthtodatefrom)
SET #Priormonthdateto= dateadd(year,-1,Dateadd(DAY,1,eomonth(#ytd,-1)))
SET #Currentmonth=dateadd(DAY,1,EOMONTH(getdate(),-1))
SELECT
b.T3,
b.Country_name,
b.Division_Name,
b.SHOP_NAME,
b.Shop_Type,
b.MTD_Result
FROM
(
SELECT
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type,
sum(case when coa.EBIT in ('EBIT') then gl.Amount ELSE 0 END) as MTD_Result
FROM
(
SELECT
s.T3,
s.DIVISION_NAME as Division_Name,
s.SHOP_NAME,
s.COUNTRY_NAME as Country_name,
s.[Business Grouping] as Shop_Type
FROM Finance_PRD.dbo.Shops s
WHERE
s.DIVISION_NAME in ('NSWACT FCB Retail North', 'NSWACT FCB Retail South', 'Vicmania', 'The Heartland', 'SA FCB Retail', 'WANT FCB Retail', 'UT Leisure', 'TA Leisure', 'Contact Centre')
and s.BUSTYPE='ARET'
and s.[Open Date] < #Currentmonth
and s.[Close Date] is null
and s.T3 = '497088'
GROUP BY
s.T3,
s.SHOP_TYPE,
s.PRIMARY_STORE_T3,
s.DIVISION_NAME,
s.t3,
s.SHOP_NAME,
s.COUNTRY_NAME,
s.[Business Grouping],
s.BUSINESS_GROUPING_NAME,
s.SHOP_NAME) a
INNER JOIN Finance_PRD.ANZ.ConsolidatedAUD as gl
on a.T3 = gl.T3
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN
CONCAT(YEAR(#Monthtodatefrom), RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Monthtodateto) <= 6 THEN
CONCAT(YEAR(#Monthtodateto), RIGHT(CONCAT('000', MONTH(#Monthtodateto) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodateto) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodateto) - 6), 3))
END
GROUP BY
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type
)b
but when I want to join on a second statement it does not return a value, I require the second statement to be 0 if there is no join.
Second part of the code is here which I set below query b
Inner join Finance_PRD.ANZ.ConsolidatedAUD as gl
on b.T3 = gl.T3
Inner JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Priormonthdatefrom) <= 6 THEN
CONCAT(YEAR(#Priormonthdatefrom), RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Priormonthdateto) <= 6 THEN
CONCAT(YEAR(#Priormonthdateto), RIGHT(CONCAT('000', MONTH(#Priormonthdateto) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdateto) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdateto) - 6), 3))
END
I've tried to understand all the different joins and even attempted to use is null, if and coalesce to no avail.
...................
LEFT JOIN
(
Finance_PRD.ANZ.ConsolidatedAUD as gl
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa on gl.AccountCode = coa.Code
) on a.T3 = gl.T3
WHERE gl.Period IS NULL OR (gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN ....)

Merge many queries into one query to speed up

I have written a procedure that collects data from 4 tables and issues a general report for the day.
There are two similar SQL queries in the procedure, the execution time of each of which is more than 1 seconds, respectively, the procedure execution time is more than 2 seconds, can this be optimized?
CREATE PROCEDURE cv
#dt AS SMALLDATETIME
AS
SELECT
(SELECT ISNULL(SUM(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa
WHERE DataRC = #dt) AS crMagPDP,
(SELECT ISNULL(SUM(SumPrice), 0) -
ISNULL(SUM(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa
WHERE DataRC = #dt) AS crMag,
for browse
2 queries are shown just as an example, there are more subqueries.
Whole procedure:
SET ANSI_NULLS OFF
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE CV
#dt as SMALLDATETIME
AS
SELECT
(SELECT isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa WHERE DataRC = #dt) as crMagPDP,
(SELECT ISNULL(sum(SumPrice), 0) - isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa WHERE DataRC = #dt) AS crMag,
(SELECT ISNULL(SUM(What_Done.Price_Sp), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Sp >= 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crParts,
(SELECT ISNULL(SUM(What_Done.Price_Total - ISNULL(What_Done.Price_Diag, 0)), 0)
FROM What_Done INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total > 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) + (SELECT ISNULL(SUM(What_Done.Price_Diag), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
) as crCassa,
(SELECT ISNULL(SUM(What_Done.Price_Diag), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_IN <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
) + (SELECT ISNULL(SUM(What_Done.Price_Total - ISNULL(What_Done.Price_Diag, 0)), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_OUT <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crBCard,
(SELECT ISNULL(SUM(Summ), 0) FROM RevOrd WHERE Summ >= 0 AND Nal <> 0 AND DateOrd = #dt) as crNal,
(SELECT ISNULL(SUM(Summ), 0) FROM RevOrd WHERE Summ >= 0 AND Nal = 0 AND DateOrd = #dt) as crCard,
(SELECT ISNULL(Sum(SumTotal), 0) FROM LineOrders WHERE DataOut = #dt) as crLine,
(SELECT ISNULL(Sum(SumTotal), 0) FROM LineOrders WHERE DataOut = #dt and Dost <> 0) as crDostavka,
(SELECT ISNULL(SUM(What_Done.BCard_IN_Sum), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_IN <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
)+(SELECT ISNULL(SUM(What_Done.BCard_OUT_Sum), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_OUT <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crBCardCorrect
for browse
Assuming the criteria for the sub-queries are identical and filter on DataRC = #dt and use the same data source RCassa, then you can simplify the query like this:
SELECT
isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0) as crMagPDP,
ISNULL(sum(SumPrice), 0) - isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0) AS crMag,
...
FROM RCassa
WHERE DataRC = #dt
If the outer select is from other table[s] use APPLY
SELECT
isnull(t.crMagPDP, 0) crMagPDP,
isnull(t.crMag, 0) crMag,
..
FROM
..
OUTER APPLY (
SELECT
sum(CASE WHEN PrePayDate IS NULL THEN 0 ELSE Price * Kvo END) as crMagPDP,
sum(SumPrice) - sum(CASE WHEN PrePayDate IS NULL THEN 0 ELSE Price * Kvo END) AS crMag,
...
FROM RCassa
WHERE DataRC = #dt
) t

SQL Server 2012 query / Job

I have a pretty complex SQL query that I need run every Monday morning (early).
I've gotten the SQL query to give me the data I need but i'm at a loss how to have the query insert the results into a table.
The declare statements are causing the issue (I THINK)
Does anyone have any ideas? Ideally I'd like to setup a job that just runs and appends to a table.
Thanks.
K.
DECLARE #StartDateTime DATETIME;
DECLARE #EndDateTime DATETIME;
DECLARE #ReportOn CHAR(1);
DECLARE #Group1 VARCHAR(25);
DECLARE #Group2 VARCHAR(25);
DECLARE #Date1Grouping VARCHAR(25);
DECLARE #Date2Grouping VARCHAR(25);
DECLARE #DivisionID VARCHAR(10);
DECLARE #GroupSubsidiaries BIT;
SET #StartDateTime = '3/06/2013' ;
SET #EndDateTime = '3/12/2013' ;
SET #ReportOn = 'S' ;
SET #Group1 = 'Due Date' ;
SET #Group2 = 'Sale Date' ;
SET #Date1Grouping = 'Yearly' ;
SET #Date2Grouping = 'Daily' ;
SET #GroupSubsidiaries = 1 ;
DECLARE #GLEntries TABLE (ID INT PRIMARY KEY, Amount FLOAT, EntryDateTime DATETIME, GLClassificationType INT,
GroupID INT, GLAccountID INT, GLAccountClassTypeID INT, AccountID INT,
TransHeaderID INT, TransDetailID INT, DivisionID INT,
Classification INT, IsTaxable BIT, TaxClassID INT,
GoodsItemID INT, GoodsItemClassTypeID INT);
-- 'C' used for Closed Reports
IF ( #ReportOn = 'C' )
INSERT INTO #GLEntries
SELECT GL.ID, GL.Amount, GL.EntryDateTime, GL.GLClassificationType,
GL.GroupID, GL.GLAccountID, GL.GLAccountClassTypeID, GL.AccountID,
GL.TransactionID, GL.TransDetailID, GL.DivisionID,
GL.Classification, GL.IsTaxable, GL.TaxClassID,
GL.GoodsItemID, GL.GoodsItemClassTypeID
FROM GL WITH(NOLOCK)
WHERE (GL.GLAccountID <> 53)
AND EXISTS( SELECT 1
FROM TransHeader
WHERE ClosedDate BETWEEN #StartDateTime and #EndDateTime
AND ID = GL.TransactionID )
ELSE
INSERT INTO #GLEntries
SELECT GL.ID, GL.Amount, GL.EntryDateTime, GL.GLClassificationType,
GL.GroupID, GL.GLAccountID, GL.GLAccountClassTypeID, GL.AccountID,
GL.TransactionID, GL.TransDetailID, GL.DivisionID,
GL.Classification, GL.IsTaxable, GL.TaxClassID,
GL.GoodsItemID, GL.GoodsItemClassTypeID
FROM GL WITH(NOLOCK)
WHERE (GL.GLAccountID <> 53)
AND GL.EntryDateTime between #StartDateTime and #EndDateTime
;
SELECT Orders.*, Totals.*,
( SELECT -Sum(Amount)
FROM #GLEntries GL1
LEFT JOIN TransHeader TH ON (TH.ID = GL1.TransHeaderID)
WHERE GL1.GLClassificationType = 2005)
as TotalTaxes,
#StartDateTime as theStartDate,
#EndDateTime as theEndDate,
-- Selects Group1 based on #Group1
CASE
WHEN #Group1 = 'Product' THEN Product
WHEN #Group1 = 'None' THEN 'None'
WHEN #Group1 = 'Due Date' THEN
CASE
WHEN #Date1Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.DueDate, 112)
WHEN #Date1Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw,Orders.DueDate) + 1, Orders.DueDate), 112 )
WHEN #Date1Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.DueDate) * 100 + DatePart(mm,Orders.DueDate) AS VARCHAR(7) )
WHEN #Date1Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.DueDate) AS VARCHAR(4) )
END
WHEN #Group1 = 'Sales Date' THEN
CASE
WHEN #Date1Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.EntryDateTime, 112 )
WHEN #Date1Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw,Orders.EntryDateTime) + 1, Orders.EntryDateTime), 112 )
WHEN #Date1Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) * 100 + DatePart(mm, Orders.EntryDateTime) AS VARCHAR(7) )
WHEN #Date1Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) AS VARCHAR(4) )
END
WHEN #Group1 = 'Primary Salesperson' THEN Salesperson1LastName + Salesperson1FirstName
WHEN #Group1 = 'Customer Origin' THEN OriginName
WHEN #Group1 = 'Industry' THEN IndustryName
WHEN #Group1 = 'Order Origin' THEN OrderOriginName
WHEN #Group1 = 'Postal Code' THEN PostalCode
WHEN #Group1 = 'Postal Code 3 Digit' THEN PostalCode3Digit
WHEN #Group1 = 'Product Category' THEN ProductCategory
WHEN #Group1 = 'Account' THEN AccountName
WHEN #Group1 = 'Company Name' THEN CompanyName
WHEN #Group1 = 'Company Frequency' THEN CompanyName
WHEN #Group1 = 'Company Volume' THEN CompanyName
WHEN #Group1 = 'GL Department' THEN GLDepartment
WHEN #Group1 = 'Industry (Parent)' THEN IndustryParent
WHEN #Group1 = 'Company Origin (Parent)' THEN CompanyOriginParent
WHEN #Group1 = 'Order Origin (Parent)' THEN OrderOriginParent
WHEN #Group1 = 'Region' THEN RegionName
END AS Group1,
CASE
WHEN #Group2 = 'Product' THEN Product
WHEN #Group2 = 'None' THEN 'None'
WHEN #Group2 = 'Due Date' THEN
CASE
WHEN #Date2Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.DueDate, 112 )
WHEN #Date2Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw, Orders.DueDate) + 1, Orders.DueDate), 112 )
WHEN #Date2Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.DueDate) * 100 + DatePart(mm, Orders.DueDate) AS VARCHAR(7) )
WHEN #Date2Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.DueDate) AS VARCHAR(4) )
END
WHEN #Group2 = 'Sales Date' THEN
CASE
WHEN #Date2Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.EntryDateTime, 112 )
WHEN #Date2Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw, Orders.EntryDateTime) + 1, Orders.EntryDateTime), 112 )
WHEN #Date2Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) * 100 + DatePart(mm, Orders.EntryDateTime) AS VARCHAR(7) )
WHEN #Date2Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) AS VARCHAR(4) )
END
WHEN #Group2 = 'Primary Salesperson' THEN Salesperson1LastName + Salesperson1FirstName
WHEN #Group2 = 'Customer Origin' THEN OriginName
WHEN #Group2 = 'Industry' THEN IndustryName
WHEN #Group2 = 'Order Origin' THEN OrderOriginName
WHEN #Group2 = 'Postal Code' THEN PostalCode
WHEN #Group2 = 'Postal Code 3 Digit' THEN PostalCode3Digit
WHEN #Group2 = 'Product Category' THEN ProductCategory
WHEN #Group2 = 'Account' THEN AccountName
WHEN #Group2 = 'Company' THEN CompanyName
WHEN #Group2 = 'GL Department' THEN GLDepartment
WHEN #Group2 = 'Region' THEN RegionName
END AS Group2
FROM ( SELECT 1 AS StoreID,
fx_Return.DivisionID,
EmployeeGroup.DivisionName,
fx_Return.TransHeaderID,
fx_Return.OrderNumber,
fx_Return.InvoiceNumber,
fx_Return.CompanyName,
-fx_Return.GLAmount AS Amount,
GLAccount.AccountName,
fx_Return.StatusText,
fx_Return.Classification,
fx_Return.GLClassificationType,
fx_Return.Description,
fx_Return.EntryDateTime,
fx_Return.DiscountPrice,
fx_Return.SaleDate,
fx_Return.DueDate,
fx_Return.BuiltDate,
fx_Return.OrderCreatedDate,
fx_Return.ClosedDate,
fx_Return.AccountID,
fx_Return.GLDepartment,
fx_Return.SalesPerson1ID,
SalesPerson1.FirstName AS SalesPerson1FirstName,
SalesPerson1.LastName AS SalesPerson1LastName,
Origin.ItemName AS OriginName,
CASE
WHEN Origin.ParentID = 11 THEN Origin.ItemName
ELSE CompanyOriginParent.ItemName
END AS CompanyOriginParent,
Industry.ItemName AS IndustryName,
CASE
WHEN IndustryParent.ID = 10 THEN Industry.ItemName
ELSE IndustryParent.ItemName
END AS IndustryParent,
fx_Return.OrderOriginName,
CASE
WHEN OrderOrigin.ParentID = 13 THEN OrderOrigin.ItemName
ELSE OrderOriginParent.ItemName
END AS OrderOriginParent,
Address.PostalCode,
SUBSTRING(Address.PostalCode,1,3) AS PostalCode3Digit,
Product.ItemName AS Product,
ProductCategory.ElementName AS ProductCategory,
ProductSubCategory.ElementName AS ProductSubCategory,
Region.ItemName AS RegionName
FROM ( SELECT GL2.EntryDateTime,
SUM( CASE
WHEN #ReportOn NOT IN ('P','B') THEN GL2.Amount
WHEN GL2.GLAccountID IN (11, 12) THEN -GL2.Amount
WHEN GL2.GLClassificationType IN (4000, 2005) THEN GL2.Amount
ELSE 0
END ) AS GLAmount,
GL2.GLAccountID,
CASE
WHEN GL2.GLClassificationType IN (4000,5002)
AND COALESCE(GL2.Classification,-1) NOT IN (100,200,300,400,500) THEN 100
ELSE GL2.Classification
END AS Classification,
GL2.GLClassificationType,
GL2.DivisionID,
GL2.IsTaxable,
GL2.TaxClassID,
GL2.GroupID,
TransHeader.StatusText,
CAST(TransHeader.Description AS VARCHAR(30)) AS Description,
TransHeader.DueDate,
TransHeader.OrderOriginName,
-- TransHeader Related Fields
GL2.TransHeaderID,
TransHeader.OrderNumber,
COALESCE( TransHeader.InvoiceNumber, TransHeader.OrderNumber) as InvoiceNumber,
TransHeader.CreditMemoOrderID,
TransHeader.Salesperson1ID,
TransHeader.OrderOriginID,
TransHeader.InvoiceAddressID as OrderInvoiceAddressID,
TransHeader.PromotionID,
Transheader.DiscountPrice,
TransHeader.PricingLevelID,
TransHeader.ClosedDate,
TransHeader.OrderCreatedDate,
TransHeader.SaleDate,
TransHeader.BuiltDate,
-- TransDetail Related Fields
GL2.TransDetailID,
TransDetail.LineItemNumber,
TransDetail.Quantity,
GL2.GoodsItemID,
GL2.GoodsItemClassTypeID,
TransDetail.GoodsItemCode,
Station.StationName as GLDepartment,
-- Account Related Fields
GL2.AccountID,
ParentAccount.CompanyName,
ParentAccount.AccountNumber,
ParentAccount.PricingPlanTypeID,
ParentAccount.IndustryID,
ParentAccount.RegionID,
ParentAccount.OriginID as CompanyOriginID,
ParentAccount.Marketing3ID,
ParentAccount.BillingAddressID as CompanyBillingAddressID
FROM #GLEntries GL2
LEFT JOIN TransHeader WITH(NOLOCK) ON (TransHeader.ID = GL2.TransHeaderID)
LEFT JOIN Account WITH(NOLOCK) ON (Account.ID = GL2.AccountID)
LEFT JOIN Account ParentAccount WITH(NOLOCK) ON ParentAccount.ID = ( CASE WHEN #GroupSubsidiaries = 1 THEN COALESCE(Account.ParentID, Account.ID) ELSE Account.ID END )
LEFT JOIN TransDetail WITH(NOLOCK) ON (TransDetail.ID = GL2.TransDetailID)
LEFT JOIN Station WITH(NOLOCK) ON TransDetail.GLDepartmentID = Station.ID
WHERE ( GL2.GLClassificationType IN (4000)
OR ( #ReportOn = 'B' AND GL2.GLAccountID in (12) )
OR ( #ReportOn = 'P' AND GL2.GLAccountID in (11,12) )
)
GROUP BY GL2.EntryDateTime,
GL2.GLAccountID,
GL2.GLAccountClassTypeID,
GL2.Classification,
GL2.GLClassificationType,
GL2.DivisionID,
GL2.IsTaxable,
GL2.TaxClassID,
GL2.GroupID,
-- TransHeader Related Fields
GL2.TransHeaderID,
TransHeader.OrderNumber,
COALESCE( TransHeader.InvoiceNumber, TransHeader.OrderNumber ),
TransHeader.CreditMemoOrderID,
TransHeader.Salesperson1ID,
TransHeader.OrderOriginID,
TransHeader.InvoiceAddressID,
TransHeader.PromotionID,
TransHeader.PricingLevelID,
Transheader.DiscountPrice,
TransHeader.OrderCreatedDate,
TransHeader.SaleDate,
TransHeader.ClosedDate,
TransHeader.BuiltDate,
TransHeader.StatusText,
TransHeader.DueDate,
TransHeader.OrderOriginName,
CAST(TransHeader.Description AS VARCHAR(30)),
-- TransDetail Related Fields
GL2.TransDetailID,
TransDetail.LineItemNumber,
TransDetail.Quantity,
GL2.GoodsItemID,
GL2.GoodsItemClassTypeID,
TransDetail.GoodsItemCode,
Station.StationName,
-- Account Related Fields
GL2.AccountID,
ParentAccount.CompanyName,
ParentAccount.AccountNumber,
ParentAccount.PricingPlanTypeID,
ParentAccount.IndustryID,
ParentAccount.RegionID,
ParentAccount.OriginID,
ParentAccount.Marketing3ID,
ParentAccount.BillingAddressID ) AS fx_Return
LEFT JOIN EmployeeGroup WITH(NOLOCK) ON EmployeeGroup.ID = fx_Return.DivisionID
LEFT JOIN MarketingListItem AS Origin WITH(NOLOCK) ON Origin.ID = fx_Return.CompanyOriginID
LEFT JOIN MarketingListItem AS CompanyOriginParent WITH(NOLOCK) ON Origin.ParentID = CompanyOriginParent.ID
AND Origin.ParentClassTypeID = CompanyOriginParent.ClassTypeID
LEFT JOIN MarketingListItem AS Industry WITH(NOLOCK) ON Industry.ID = fx_Return.IndustryID
LEFT JOIN MarketingListItem AS IndustryParent WITH(NOLOCK) ON Industry.ParentID = IndustryParent.ID
AND Industry.ParentClassTypeID = IndustryParent.ClassTypeID
LEFT JOIN MarketingListItem AS OrderOrigin WITH(NOLOCK) ON fx_Return.OrderOriginID = OrderOrigin.ID
LEFT JOIN MarketingListItem AS OrderOriginParent WITH(NOLOCK) ON OrderOrigin.ParentID = OrderOriginParent.ID
AND OrderOrigin.ParentClassTypeID = OrderOriginParent.ClassTypeID
LEFT JOIN Address WITH(NOLOCK) ON fx_Return.CompanyBillingAddressID = Address.ID
LEFT JOIN CustomerGoodsItem AS Product WITH(NOLOCK) ON fx_Return.GoodsItemID = Product.ID
AND Product.ClassTypeID=fx_Return.GoodsItemClassTypeID
LEFT JOIN PricingElement AS ProductCategory WITH(NOLOCK) ON Product.CategoryID = ProductCategory.ID
AND Product.CategoryClassTypeID = ProductCategory.ClassTypeID
LEFT JOIN PricingElement AS ProductSubCategory WITH(NOLOCK) ON ProductCategory.ParentID = ProductSubCategory.ID
AND ProductCategory.ParentClassTypeID = ProductSubCategory.ClassTypeID
LEFT JOIN Employee AS Salesperson1 WITH(NOLOCK) ON fx_Return.SalesPerson1ID = Salesperson1.ID
LEFT JOIN GLAccount WITH(NOLOCK) ON fx_Return.GLAccountID = GLAccount.ID
LEFT JOIN MarketingListItem AS Region WITH(NOLOCK) ON fx_Return.RegionID = Region.ID
) AS Orders
LEFT JOIN ( SELECT SUM( CASE
WHEN #ReportOn <> 'P' THEN -GL3.Amount
WHEN GL3.GLAccountID IN (11, 12, 51) THEN GL3.Amount
WHEN GL3.GLClassificationType IN (4000, 2005) THEN -GL3.Amount
ELSE 0
END ) AS CompanyTotalAmount,
COUNT(DISTINCT TransHeader.ID) AS CompanyOrderCount,
GL3.AccountID AS TotalsAccountID
FROM #GLEntries GL3
LEFT JOIN TransHeader WITH(NOLOCK) ON (TransHeader.ID = GL3.TransHeaderID)
WHERE ( GL3.GLClassificationType in (4000) -- 5002) --Kyle/Scott, we have no clue why this was included, can't think of any expense accounts you'd ever show as a sale
OR
( #ReportOn = 'B' AND GL3.GLAccountID in (12) )
OR
( #ReportOn = 'P' AND GL3.GLAccountID in (11, 12) )
)
GROUP BY GL3.AccountID ) AS Totals ON Totals.TotalsAccountID = Orders.AccountID
WHERE OrderNumber IS NOT NULL
1) OK - so you need to create a table with the same columns and same data types as in the select list (SELECT Orders.*, Totals.*...)
2) You will have to include the insert statement before the select - something like this
insert StagingTableName
select Orders.*, Totals.*...
3) Create a stored procedure with all your code in it.
4) Execute the stored procedure using a SQL Server Agent Job. This link should help.

not able call alias column name in where condition in sql server

WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
n this query i want to add one more condition like
AND LocType = 'Retail Store' and TotalHrs=0 but showing error
Invalid column name 'TotalHrs'.
How i can resolve this issue.if any help is very appreciable,thanks in advance
You can use multiple CTE's in following:
WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
, cte2 AS
(
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
)
SELECT *
FROM cte2
WHERE TotalHrs=0 --your alias condition or you can move all where clause here