I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-
SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup, VNC.productcomponent,
VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
VNC.[high %], VNC.vqi, VNC.deepcontrol,
--Modification done for CHE10045964
PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
SFG_ProductNo = CASE
WHEN UCHSC.attribute_ != P.productno
THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
RC.Name as ResourceClassName
FROM order_header OH
INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
INNER JOIN dbo. product P ON WO.productid = P.id
INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
WHERE OH.ordertype = 23
GROUP BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
CASE
WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
--Added By Sukanya Biswas(CHE10045964)
NC.WorkCenter
FROM (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
[LowUnits] = Isnull(b.[1], 0),
[Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
ELSE Isnull(b.[1], 0)
END, [HighUnits] = Isnull(b.[2], 0),
[High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
ELSE Isnull(b.[2], 0)
END ,
--Added By Sukanya Biswas(CHE10045964)
B.WorkCenter
FROM (SELECT D .orderno, SampleID = DTS.id,
--Added By Sukanya Biswas(CHE10045964)
DL.WorkCenter,
Comment = CASE Isnull(DTS.comment_, '')
WHEN '' THEN 'N/A'
ELSE DTS.comment_
END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
NC.weightingfactor, NC.ConsumerSensitive,
Severity = Isnull(QD.qualitydefectseverityid, 0),
QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
FROM dbo.disposition D
INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
--Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
AND DT.linesequenceno = DL.linesequenceno
INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
WHERE DL.linecode = 'VQ'
) A
PIVOT (Sum(a.noofdefects)
FOR severity IN ([1],[2]))
B)
NC
As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.
You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017"
Related
I was converting MySql to DB2 queries, and so far I got to this:
SELECT
loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM
(
SELECT
cl.display_name AS clientName,
cl.id AS clientId,
ln.id AS loanId,
ln.account_no AS accountId,
ln.loan_status_id AS accountStatusId,
pl.short_name AS productShortName,
ln.product_id AS productId,
ln.currency_code AS currencyCode,
ln.currency_digits AS currencyDigits,
ln.currency_multiplesof AS inMultiplesOf,
rc.name AS currencyName,
rc.display_symbol AS currencyDisplaySymbol,
rc.internationalized_name_code AS currencyNameCode,
CASE WHEN ln.loan_status_id = 200 THEN ln.principal_amount
ELSE NULL
END AS disbursementAmount,
SUM(COALESCE((CASE WHEN ln.loan_status_id = 300 THEN ls.principal_amount ELSE 0.0 END), 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.principal_completed_derived ELSE 0.0 END, 0.0)) AS principalDue,
ln.principal_repaid_derived AS principalPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_completed_derived ELSE 0.0 END, 0.0)) AS interestDue,
ln.interest_repaid_derived AS interestPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_completed_derived ELSE 0.0 END, 0.0)) AS feeDue,
ln.fee_charges_repaid_derived AS feePaid
FROM
m_loan LN
JOIN m_client cl ON
cl.id = ln.client_id
LEFT JOIN m_office OF ON
of.id = cl.office_id
AND of.hierarchy LIKE ?
LEFT JOIN m_product_loan pl ON
pl.id = ln.product_id
LEFT JOIN m_currency rc ON
rc.code = ln.currency_code
JOIN m_loan_repayment_schedule ls ON
ls.loan_id = ln.id
AND ls.completed_derived = 0
AND ls.duedate <= ?
WHERE
of.id = ?
AND (ln.loan_status_id = 300)
AND ln.group_id IS NULL
) AS loandata
LEFT JOIN m_loan_charge lc ON
lc.loan_id = loandata.loanId
AND lc.is_paid_derived = 0
AND lc.is_active = 1
AND ( lc.due_for_collection_as_of_date <= ?
OR lc.charge_time_enum = 1)
GROUP BY
loandata.clientId,
loandata.loanId
ORDER BY
loandata.clientId,
loandata.loanId
But I am getting an error :
SQL Error [42803]: An expression starting with "DISBURSEMENTAMOUNT"
specified in a SELECT clause, HAVING clause, or ORDER BY clause is not
specified in the GROUP BY clause or it is in a SELECT clause, HAVING
clause, or ORDER BY clause with a column function and no GROUP BY
clause is specified.. SQLCODE=-119, SQLSTATE=42803, DRIVER=4.26.14
I have tried inserting Group by and Order By clauses each for the select clause items like so:
SELECT
loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM
(
SELECT
cl.display_name AS clientName,
cl.id AS clientId,
ln.id AS loanId,
ln.account_no AS accountId,
ln.loan_status_id AS accountStatusId,
pl.short_name AS productShortName,
ln.product_id AS productId,
ln.currency_code AS currencyCode,
ln.currency_digits AS currencyDigits,
ln.currency_multiplesof AS inMultiplesOf,
rc.name AS currencyName,
rc.display_symbol AS currencyDisplaySymbol,
rc.internationalized_name_code AS currencyNameCode,
CASE WHEN ln.loan_status_id = 200 THEN ln.principal_amount
ELSE NULL
END AS disbursementAmount,
SUM(COALESCE((CASE WHEN ln.loan_status_id = 300 THEN ls.principal_amount ELSE 0.0 END), 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.principal_completed_derived ELSE 0.0 END, 0.0)) AS principalDue,
ln.principal_repaid_derived AS principalPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_completed_derived ELSE 0.0 END, 0.0)) AS interestDue,
ln.interest_repaid_derived AS interestPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_completed_derived ELSE 0.0 END, 0.0)) AS feeDue,
ln.fee_charges_repaid_derived AS feePaid
FROM
m_loan LN
JOIN m_client cl ON
cl.id = ln.client_id
LEFT JOIN m_office OF ON
of.id = cl.office_id
AND of.hierarchy LIKE ?
LEFT JOIN m_product_loan pl ON
pl.id = ln.product_id
LEFT JOIN m_currency rc ON
rc.code = ln.currency_code
JOIN m_loan_repayment_schedule ls ON
ls.loan_id = ln.id
AND ls.completed_derived = 0
AND ls.duedate <= ?
WHERE
of.id = ?
AND (ln.loan_status_id = 300)
AND ln.group_id IS NULL
GROUP BY
cl.display_name,
cl.id,
ln.id,
ln.account_no,
ln.loan_status_id,
pl.short_name,
ln.product_id,
ln.currency_code,
ln.currency_digits,
ln.currency_multiplesof,
rc.name,
rc.display_symbol,
rc.internationalized_name_code,
ln.loan_status_id,
ln.principal_amount,
ln.principal_repaid_derived,
ln.interest_repaid_derived,
ln.fee_charges_repaid_derived
ORDER BY
cl.display_name,
cl.id,
ln.id,
ln.account_no,
ln.loan_status_id,
pl.short_name,
ln.product_id,
ln.currency_code,
ln.currency_digits,
ln.currency_multiplesof,
rc.name,
rc.display_symbol,
rc.internationalized_name_code,
ln.loan_status_id,
ln.principal_amount,
ln.principal_repaid_derived,
ln.interest_repaid_derived,
ln.fee_charges_repaid_derived
) AS loandata
LEFT JOIN m_loan_charge lc ON
lc.loan_id = loandata.loanId
AND lc.is_paid_derived = 0
AND lc.is_active = 1
AND ( lc.due_for_collection_as_of_date <= ?
OR lc.charge_time_enum = 1)
GROUP BY
loandata.clientId,
loandata.loanId
ORDER BY
loandata.clientId,
loandata.loanId
A gross simplification of your query is:
SELECT loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM (SELECT <lots of columns>
FROM <lots of tables>
. . .
) loandata LEFT JOIN
m_loan_charge lc
ON lc.loan_id = loandata.loanId AND
lc.is_paid_derived = 0 AND
lc.is_active = 1 AND
( lc.due_for_collection_as_of_date <= ? OR lc.charge_time_enum = 1)
GROUP BY loandata.clientId, loandata.loanId
ORDER BY loandata.clientId, loandata.loanId;
You have a SELECT * bringing in lots of columns. Fine. Then you have an aggregation function -- so the query is an aggregation query. Need a GROUP BY with lots of columns.
But I don't find one. I only find a GROUP BY with two columns. And that is an error in SQL. And happily, that is now an error in the more recent versions of MySQL. And in basically every other database.
You need to list all the columns in the GROUP BY that are not aggregated in the SELECT.
I have this massive query that I am trying to add a left join to. The addition is commented out.
The main query runs < 4 sec, 32,000 rows.
The commented part runs < 1 sec, 51,000 rows.
But, when I combine them i.e join the second query, the whole thing runs in 15 sec.
There are already 2 massive joins in the original query (50,000 rows both), so I don't get why this join is special.
PS: I might also be doing other suboptimal things, please criticize.
select
*,
case
when t2.status = 1 and t2.price > t2.buyprice then round((t2.price - t2.buyprice) * 0.04, 2)
when t2.status = 2 and t2.price > t2.buyprice then round((t2.price - t2.buyprice) * 0.03, 2)
when t2.status = 3 and t2.price > t2.buyprice then round((t2.price - t2.buyprice) * 0.02, 2)
when t2.status = 4 and t2.price > t2.buyprice then round((t2.price - t2.buyprice) * 0.01, 2)
else 0
end as bonus
from (
select *,
case
when t1.gratis = 1 then 10
when t1.price_vat = 0 or t1.price = 0 then
case
when t1.stock > 0 or soldLast180DaysQty > 0 then -1
when t1.stock = 0 then 12
end
when t1.buyprice = 0 then
case
when t1.stock > 0 then -1
when t1.stock = 0 then 12
end
when soldLast180DaysQty < 0 then 1
when t1.age_days < 60 then 9
when t1.last_import <= 180 then
case
when t1.soldLast180DaysQty <= t1.stock then 0
when t1.soldLast180DaysQty > t1.stock then 7
when t1.stock = 0 then 5
end
when t1.last_import >= 180 and t1.stock = 0 then
case
when soldLast180DaysQty > 0 then 10
when soldLast180DaysQty = 0 then 11
end
when t1.last_import >= 180 then
case
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) < 0.3 and t1.stock_retail / t1.stock >= 0.9 then 5
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0 and 0.1 then 1
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.1 and 0.2 then 2
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.2 and 0.3 then 3
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.3 and 0.4 then 4
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.4 and 0.7 then 0
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) >= 0.9 then 6
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.8 and 0.9 then 7
when t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) between 0.7 and 0.8 then 8
end
end as status,
round(t1.soldLast180DaysQty / nullif(t1.stock + t1.soldLast180DaysQty, 0) * 100, 0) as ratio
from (
select
si.anqid id,
CAST(rtrim(si.acident) as nvarchar(7)) as code,
CAST(rtrim(si.acname) as nvarchar(100)) as name,
si.anvat as vat,
si.ansaleprice as price_vat,
round(si.anrtprice, 2) as price,
cenovnik.clientPrice, -- <---------------------- This part
round(si.anbuyprice, 2) as buyprice,
concat(round(anpricesupp, 2), ' ', acpurchcurr) as fakturna,
round(si.anrtprice - si.anbuyprice, 2) as profit,
case
when si.anrtprice is not null and si.anrtprice > 0 and si.anbuyprice is not null and si.anbuyprice > 0
then round((si.anrtprice / si.anbuyprice - 1) * 100, 0)
end as margin,
cast(si.acfieldsa as nvarchar(12)) as [group],
cast(rtrim(si.acClassif2) as nvarchar(16)) as category,
cast(rtrim(ss.acsubject) as nvarchar(7)) as supplier_code,
cast(left(ss.acname2, 30) as nvarchar(30)) as supplier_name,
rtrim(si.acclassif) as rebate,
si.anFieldNA as webActive,
si.anfieldNF as gratis,
case
when si.acpicture is not null then 'true'
else 'false'
end as picture,
isnull((select sum(anstock) from the_stock where acident = si.acident and acwarehouse = '00051'), 0) as stock_warehouse,
isnull((select sum(anstock) from the_stock where acident = si.acident and acwarehouse <> '00051'), 0) as stock_retail,
isnull((select sum(anstock) from the_stock where acident = si.acident), 0) as stock,
isnull((select sum(anReserved) from the_stock where acident = si.acident), 0) as stock_reserved,
isnull((select sum(anvalue) from the_stock where acident = si.acident), 0) as stock_value,
(
select isnull(datediff(day, max(m.addate), getdate()), 9999)
from the_moveitem mi
left join the_move m
on mi.ackey = m.ackey
where mi.acident = si.acident and m.acDocType in ('1900', '1000', '6800', '1A00')
) as last_import,
isnull(round(soldLast180Days.soldLast180DaysQty, 0), 0) soldLast180DaysQty,
isnull(round(soldLast180Days.soldLast180DaysCogs, 0), 0) soldLast180DaysCogs,
isnull(round(soldLast180Days.soldLast180DaysRevenue, 0), 0) soldLast180DaysRevenue,
isnull(round(soldLast180Days.soldLast180DaysProfit, 0), 0) soldLast180DaysProfit,
datediff(day, si.adtimeins, getdate()) as age_days
from the_setitem si
/*
left join (
SELECT
si.acident sku,
case
when dogovoren.anPrice is null and matrica.anRebate is null then si.anRTPrice
when dogovoren.anPrice is not null then dogovoren.anPrice
when dogovoren.anPrice is null then si.anRTPrice * (1 - matrica.anRebate/100)
end as clientPrice
FROM tHE_SetItem si
left join (
select acident, anPrice
from vHE_SetSubjPriceItemExtToday
where acsubject = '1111'
) dogovoren
on dogovoren.acident = si.acident
left join (
select acClassif, anRebate
from vHE_SetSubjTypePriceCateg
where acSubjType = (select acsubjtypebuyer from tHE_SetSubj where acsubject = '1111')
) matrica
on si.acClassif = matrica.acClassif
) cenovnik
on cenovnik.sku = si.acident
*/
left join tHE_SetSubj ss
on ss.acsubject = si.acsupplier
left join (
select
mi.acident,
sum(mi.anQty) soldLast180DaysQty,
sum(mi.anQty * mi.anStockPrice) soldLast180DaysCogs,
sum(mi.anPVVATBase) soldLast180DaysRevenue,
sum(mi.anPVVATBase - mi.anQty * mi.anStockPrice) soldLast180DaysProfit
from the_moveitem mi
left join the_move m
on m.ackey = mi.ackey
where m.acDocType in ('3000', '3050', '3190', '3800', '3550', '3X10', '3950', '3500', '3510', '6700', '3A00', '3210', '3220', '3230', '3240', '3450', '3250', '3260', '3270', '3540', '3460', '3280', '3290', '3310', '3320', '3440', '3330', '3340', '3350', '3360', '3370', '3380', '3390', '3410', '3470', '3420', '3430', '3480', '3490', '3520', '3530', '3560', '3610', '2540', '2740', '2730'
) and m.addate >= getdate() - 180
group by mi.acident
) soldLast180Days
on soldLast180Days.acIdent = si.acident
) t1
) t2
where
t2.status < 11
order by
t2.status asc,
t2.stock_value desc
I am using SQL Server if it's relevant.
Not really an answer - but when I've had this problem I've just created temporary tables. In SQL Server you prefix the table name with # and they will get deleted when your session ends.
You might realise your nested table t1 as a temporary table #t1
CREATE TABLE #t1 (id INT, code NVARCHAR(7), etc...)
INSERT INTO #t1
select
si.anqid id,
CAST(rtrim(si.acident) as nvarchar(7)) as code,
CAST(rtrim(si.acname) as nvarchar(100)) as name,
etc..
SELECT * FROM .... #t1 ...
Replace all references to t1 with #t1
Im having a problem with this :( is this because of my select statement? or any join? derived table? or my CASE syntax?
The error occurs the time I put this CASE syntax: CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2
because before it is just:
CASE WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
SELECT Start, UserDefined3, ItemNo, Name, TotalQtyRequired, PreviouslyCounted, QtyLeftToPick, LocationCode, Location, Rack, QtyInRack, PickQty, CellCode, UDMaterial, UDMaterialSort, ScheduleTimeFROM (SELECT dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
AS TotalQtyRequired, ISNULL(RackedInventory.PreviouslyCounted, 0) AS PreviouslyCounted, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
- ISNULL(RackedInventory.PreviouslyCounted, 0) AS QtyLeftToPick, RackedInventory.LocationCode, RackedInventory.Location, RackedInventory.Rack, ISNULL(RackedInventory.QtyInRack, 0) AS QtyInRack,
ISNULL(CASE WHEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
< RackedInventory.QtyInRack THEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
ELSE RackedInventory.QtyInRack END, 0) AS PickQty, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2 AS UDMaterial, CASE WHEN dbo.ItemSpecs.Userdefined2 IN ('Foam', 'Wood',
'Plastic Inner', 'Rubber') THEN 0 ELSE 1 END AS UDMaterialSort, CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
FROM dbo.ToBeScheduled_InProgress INNER JOIN
dbo.OpenCalendarDaysTable AS OpenCalendarDays ON dbo.ToBeScheduled_InProgress.Start BETWEEN OpenCalendarDays.CalendarDateForwardRangeStart AND
OpenCalendarDays.CalendarDateForwardRangeEnd AND OpenCalendarDays.CalendarLinkID IS NULL INNER JOIN
dbo.OpenCalendarDaysTable AS PriorOpenCalendarDays ON OpenCalendarDays.CalendarOpenDayID = PriorOpenCalendarDays.CalendarOpenDayID + 1 AND OpenCalendarDays.CalendarLinkID IS NULL
INNER JOIN
dbo.ItemSpecFullStruc ON dbo.ToBeScheduled_InProgress.ItemSpecID = dbo.ItemSpecFullStruc.RootItemSpecID INNER JOIN
dbo.ItemSpecs ON dbo.ItemSpecFullStruc.ChildItemSpecID = dbo.ItemSpecs.ItemSpecID LEFT OUTER JOIN
dbo.WorkOrder ON dbo.ToBeScheduled_InProgress.WorkOrderID = dbo.WorkOrder.WorkOrderID LEFT OUTER JOIN
(SELECT InventoryByLocation.ItemID, InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack,
InventoryByLocation.QtyInRack, SUM(PreviouslyCounted.QtyInRack) AS PreviouslyCounted
FROM (SELECT Rack, SUM(ISNULL(QtyToStock, ' ')) AS QtyInRack, ItemID, ItemSpecID, LocationID
FROM dbo.InventoryItems WITH (NOLOCK)
GROUP BY ItemID, ItemSpecID, LocationID, Rack) AS PreviouslyCounted RIGHT OUTER JOIN
(SELECT Items_1.ItemNo, Items_1.Name AS ItemDescription, Locations_1.LocationCode, Locations_1.DescriptionMed AS Location, InventoryItems_1.Rack,
SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) AS QtyInRack, UOMs_1.UOMCode AS StockUOM, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID
FROM dbo.Items AS Items_1 WITH (NOLOCK) INNER JOIN
dbo.Locations AS Locations_1 WITH (NOLOCK) INNER JOIN
dbo.InventoryItems AS InventoryItems_1 WITH (NOLOCK) LEFT OUTER JOIN
dbo.UOMs AS UOMs_1 WITH (NOLOCK) ON InventoryItems_1.StockUOMID = UOMs_1.UOMID ON Locations_1.LocationID = InventoryItems_1.LocationID ON
Items_1.ItemID = InventoryItems_1.ItemID
WHERE (Locations_1.LocationID = 7)
GROUP BY Locations_1.LocationCode, Items_1.ItemNo, Locations_1.DescriptionMed, Items_1.Name, UOMs_1.UOMCode, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID, InventoryItems_1.Rack
HAVING (SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) > 0)) AS InventoryByLocation ON PreviouslyCounted.Rack < InventoryByLocation.Rack AND
PreviouslyCounted.LocationID = InventoryByLocation.LocationID AND PreviouslyCounted.ItemID = InventoryByLocation.ItemID
GROUP BY InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack, InventoryByLocation.QtyInRack,
InventoryByLocation.ItemID) AS RackedInventory ON dbo.ItemSpecs.ItemID = RackedInventory.ItemID
WHERE (dbo.ToBeScheduled_InProgress.ExcludeFromFiniteScheduling = 0) AND (ISNULL(dbo.ItemSpecs.Userdefined2, '') <> 'Covering') AND (dbo.ItemSpecs.InventoryTrackingID > 1)
GROUP BY dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, RackedInventory.Rack, ISNULL(RackedInventory.PreviouslyCounted, 0), RackedInventory.Location,
RackedInventory.LocationCode, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2,
CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw, dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625)
- 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END, RackedInventory.QtyInRack
HAVING (SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0) > 0)) AS _RackSort_Lean_AMPM ORDER BY Start, LocationCode, Rack
SELECT SUM(nvl(DYRCVDWT, 0)) + SUM(nvl(RCVDWT, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0)) INTO netwt
FROM YARNLEDGER yl
(SELECT D.PROFILECODE, MAX(CLOSINGDATE)SDATE FROM PARTYSTOCKCLOSING D WHERE D.DEPT = 'Y' AND NVL(D.POSTED, 'N') = 'Y' GROUP BY D.PROFILECODE) SAD
WHERE yl.PROFILECODE = :PROFILECODE
AND Yl.PROFILECODE = SAD.PROFILECODE(+)
AND Yl.DOCUMENTDATE>SAD.SDATE
there are missing a comma in the FROM after the "yarnledger yl"
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl ,(SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode) sad
WHERE yl.profilecode = :profilecode
AND yl.profilecode = sad.profilecode(+)
AND yl.documentdate > sad.sdate
next time use a clearer query structure:
WITH sad as (SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode)
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl
LEFT OUTER JOIN sad
ON yl.profilecode = sad.profilecode
AND yl.documentdate > sad.sdate
WHERE yl.profilecode = :profilecode
I am having a view which returns value to a table. The process takes a long time... So I felt it works better if go for indexing on view. Can anyone plz guide me to add index to view.
ALTER View [dbo].[GetApplicationBudgetAndUtilized]
as
Select *, (convert(money,isnull(TotalBudget,0)) - convert(money,isnull(Utilized,0))) as [Left] from (
SELECT Distinct PM.PKID AS ProgramID, F.PKID as FundID, I.PKID as ProjectID,
MYB.PKID AS MultiYearBudgetID,
(Select Isnull(Sum(IsNull(PBC1.BudgetAmount,0)),0) from ProgramBudgetConfiguration PBC1
Where pbc1.MultiYearBgtIdFkId = pbc.MultiYearBgtIdFkId and PBC1.IsActive = 1 and LOVBudgetTypeIDFKID = 'BT_INC' group
by pbc1.MultiYearBgtIdFkId) AS TotalProgramBudget,
App.TotalBudget,
I.PKID,
(Case when exists (Select 'x' from InstallationTransactionHeader Where ParentPrjNumber = I.PKID and IsDelete = 0)
then
(case
when not exists (select cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)
from InstallationTransactionHeader I1 where I1.ParentPrjNumber is not null and I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and
I1.ParentPrjNumber = I.PKID and I1.FundRequestIDFKID is not null) then (select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and I1.ParentPrjNumber is not null and
I1.ParentPrjNumber = I.PKID and I1.isdelete = 0 and I1.FundRequestIDFKID is not null group by I1.parentPrjNumber)
End)
else
--isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0)
(case
when not exists (select isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0) from
InstallationTransactionHeader I where StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and
PKID = I.PKID and I.FundRequestIDFKID is not null) then 0--(select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and I1.FundRequestIDFKID is not null and
PKID = I.PKID)
End)
End) as Utilized
--Cast(App.TotalBudget - (isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00)) as Money) as [Left]
FROM
( SELECT PKID as FundID, ProgramID AS ProgramID, (ISNULL(IncentiveAmount,0.00) + ISNULL(CustInstallIncAmt, 0.00) + ISNULL(SPInstIncentiveAmt, 0.00) ) AS TotalBudget
FROM dbo.FundRequestHeader AS F WHERE (IsDelete = 0) AND (IsActive = 1) AND (StatusFKID in ('IAS_APP','IAS_CAN'))) AS App
INNER JOIN dbo.ProgramMaster AS PM
INNER JOIN dbo.MultiYearBudget AS MYB ON PM.PKID = MYB.ProgramIDFKID
INNER JOIN dbo.ProgramBudgetConfiguration AS PBC ON MYB.PKID = PBC.MultiYearBgtIdFkId ON App.ProgramID = PM.PKID
INNER JOIN dbo.FundRequestHeader AS F ON F.PKID = App.FundID
INNER JOIN dbo.InstallationTransactionHeader AS I ON I.FundRequestIDFKID = F.PKID
WHERE (PM.IsActive = 1) AND (MYB.IsActive = 1) AND (PBC.IsActive = 1) AND
(PBC.LOVBudgetTypeIDFKID = 'BT_INC') And (F.StatusFKID in ('IAS_APP','IAS_CAN'))
--and (1=case when(select ProgramTypeIDFKID from InstallationTransactionHEader where ProgramTypeIDFKID='IT_PRE' and ParentPrjNumber is null and PaymentSchedule=1)='IT_PRE' then 0 else 1 end)
--and I.ProgramTypeIDFKID <> 'IT_PRE' or I.PaymentSchedule = 0 or (I.ProgramTypeIDFKID = 'IT_PRE' and I.PaymentSchedule = 1 and I.ParentPrjNumber is not null)
and MYB.PKID = F.BudgetPeriodID and ((MYB.IsActive = 1))-- or ((MYB.status = 0) and F.StatusFKID ='IAS_APP'))
and (MYB.Status = 1 or (MYB.Status =(case when exists(select M.status from MultiYearBudget M, FundRequestHeader F
where F.ProgramID=M.ProgramIDFKID and F.ProgramTypeIDFKID <>'IT_FCFS' and M.Pkid=F.BudgetPeriodID
and F.StatusFKID='IAS_APP' and F.ProgramID=PM.PKID and M.Status=0 )then 0 else 1 end))
)
)temp
GO
Indexed views have certain limitations
In your case, I can immediately see some blockers
SELECT *
Derived tables
So read this article, and see how far you get...
However, you should be able to look the execution plan identify bottlenecks where you can add indexes to the bases tables