Performance Issue in Select groupby - sql

I have following block of code and It takes approx 4-5 minutes to execute. All the tables in this block has large amount of data.
Select
spa.Student_Id,
Cast(Case When ISNULL(#PeriodNumbers, '') = '' Then --PeriodCode Come
CPS.PeriodIdentifier
Else --period number come
Cast(SPA.PeriodNumber as varchar)
End As varchar) As Period,
IsNULL(Count(*), 0) As TotalCount,
AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar) As PeriodNumber
From
(Select Student_ID
From OpenXml(#Handle,'/NewDataSet/Table', 2)
With (Student_ID int) As DT
) FilterDT
Inner Join
dbo.StudentPeriodicAttendanceArchive SPA WITH(NOLOCK) On FilterDT.Student_ID = SPA.Student_ID
Inner Join
dbo.AcademicYear AY WITH(NOLOCK) On AY.AYIdentifier = #AYIdentifier
And AY.School_Domain = #School_Domain
Inner join
dbo.CPsession CPS WITH(NOLOCK) On CPS.SSEC_ID = SPA.SSEC_ID
And CPS.PeriodNumber= spa.periodnumber
And CPS.School_Domain = #School_Domain
And CPS.AYIdentifier = #AYIdentifier
And (CPS.CPSDelStatus = 0 Or CPS.CPSDelStatus Is Null)
Inner Join
dbo.BellTimingScheduleStructure BTSS WITH(NOLOCK) ON BTSS.DayNumber = CPS.WD_ID
And BTSS.SchedulingWeek = CPS.Week
Inner Join
dbo.ClassPeriods CP WITH(NOLOCK) On CP.CP_Id = CPS.CP_ID
And BTSS.CPR_ID = CP.CPR_ID
And BTSS.WeekDay = Case When BTSS.CPRType='D' Then BTSS.WeekDay Else CP.WD_ID End
And BTSS.DayNumber = Case When BTSS.CPRType='D' Then CP.WD_ID Else BTSS.DayNumber End
And BTSS.SchedulingWeek = Case When BTSS.CPRType='W' Then BTSS.SchedulingWeek Else CP.Week End
And BTSS.DateItem = SPA.Attdate
And CP.CPDelStatus = '0'
And IsNull(CP.IsLocked, '0') = '0'
Inner Join
dbo.AttendanceCodes AC WITH(NOLOCK) On AC.AC_ID = SPA.AttCode_ID
Where
SPA.School_Domain = #School_Domain
And AttDate >= Case When #IsYearLongTotals=1 then AY.AYStartDate Else #ActualStartDate End
And AttDate <= Case When #IsYearLongTotals=1 then AY.AYEndDate Else #ActualEndDate End
And IsNull(#Subject_ID, -1) = Case When IsNull(#Subject_ID, -1) <> -1
Then CPS.Subject_ID
Else IsNull(#Subject_ID, -1)
End
Group By
spa.Student_ID,
Cast(Case When ISNULL(#PeriodNumbers, '') = ''
Then CPS.PeriodIdentifier
Else
Cast(SPA.PeriodNumber as varchar)
End As varchar), AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar)
I have a table StudentPeriodicAttendanceArchive which contains attendance information. I want to calculate total present and absent count.
Please suggest what should I do to improve the performance. I am using SQL Server 2008 R2

Related

How to speed up a SQL query which is using DISTINCT

From what I have read about this it seems like the best solution is to create an INDEX but I am not sure which columns I should be creating indexes for. This is my first time working with SQL indexes.
If I remove the DISTINCT call from this query I get over 1000 results in just over a second. However with the DISTINCT call it returns the results in 10 seconds (obviously without the duplicates).
If anyone has any alternative solutions I am all ears.
This is the query (the second SELECT is where the DISTINCT function is called):
SELECT
Sku,
Name,
ccp.Polygon,
MarketAvailability,
Coverage,
Range
FROM
(SELECT DISTINCT
dbo.CatalogEntry.CatalogEntryId as Id,
dbo.CatalogEntry.Code as Sku,
CoverageNode.Name as Coverage,
RangeNode.Name as [Range],
(SELECT CatalogContentProperty.LongString
FROM CatalogContentProperty
WHERE MetaFieldName = 'ItemChartName'
AND (CatalogContentProperty.LongString IS NOT NULL)
AND (CatalogContentProperty.ObjectId = dbo.CatalogEntry.CatalogEntryId)) AS [Name],
(SELECT CatalogContentProperty.LongString
FROM CatalogContentProperty
WHERE MetaFieldName = 'MarketAvailabilityDetailsCollection'
AND (CatalogContentProperty.LongString IS NOT NULL)
AND (CatalogContentProperty.ObjectId = dbo.CatalogEntry.CatalogEntryId)) AS MarketAvailability
FROM
dbo.CatalogEntry
INNER JOIN
dbo.NodeEntryRelation ON dbo.CatalogEntry.CatalogEntryId = dbo.NodeEntryRelation.CatalogEntryId
INNER JOIN
dbo.CatalogNode AS CoverageNode ON dbo.NodeEntryRelation.CatalogNodeId = CoverageNode.CatalogNodeId
INNER JOIN
dbo.CatalogNode AS RangeNode ON CoverageNode.ParentNodeId = RangeNode.CatalogNodeId
INNER JOIN
dbo.CatalogContentProperty ON dbo.CatalogEntry.CatalogEntryId = dbo.CatalogContentProperty.ObjectId
INNER JOIN
dbo.CatalogNode AS ModelNode ON RangeNode.ParentNodeId = ModelNode.CatalogNodeId
INNER JOIN
dbo.CatalogNode AS BrandNode ON ModelNode.ParentNodeId = BrandNode.CatalogNodeId
WHERE
(dbo.CatalogEntry.ClassTypeId = N'Variation') AND
(dbo.CatalogContentProperty.MetaFieldName = N'ItemIsChart') AND
RangeNode.Name != 'C-MAP' AND
(BrandNode.Name = '' OR '' = '' OR '' IS NULL) AND
(ModelNode.Name = '' OR '' = '' OR '' IS NULL) AND
(CoverageNode.Name = '' OR '' = '' OR '' IS NULL) AND
(RangeNode.Name = '' OR '' = '' OR '' IS NULL)
) AS CmapResults
INNER JOIN
(SELECT
GEOMETRY::STGeomFromText(CatalogContentProperty.LongString,4326) AS PolygonGeometry,
CatalogContentProperty.LongString AS Polygon,
CatalogContentProperty.ObjectId
FROM
CatalogContentProperty
WHERE
MetaFieldName = 'ItemChartCoordinates' AND
(CatalogContentProperty.LongString IS NOT NULL)) ccp ON ccp.ObjectId = CmapResults.Id
WHERE
((GEOGRAPHY::STGeomFromText(PolygonGeometry.MakeValid().STUnion(PolygonGeometry.MakeValid().STStartPoint()).STAsText(), 4326).STDistance(GEOGRAPHY::STGeomFromText('POINT(50.9835929 -1.4205852)', 4326)) / 1609.344) <= 100 OR 'POINT(50.9835929 -1.4205852)' IS NULL)
AND MarketAvailability IS NOT NULL
ORDER BY
GEOGRAPHY::STGeomFromText(PolygonGeometry.MakeValid().STUnion(PolygonGeometry.MakeValid().STStartPoint()).STAsText(), 4326).STArea() DESC;
I am using SQL Server Management Studio 2012. The aim is to get the query with the DISTINCT call to return in the same amount of time as the query would without the DISTINCT call.
Your query looks a bit complicated. Will this one produce the same output?
SELECT DISTINCT ce.Code as Sku
, max(case when ccp.MetaFieldName = 'ItemChartName' then ccp.LongString end) as 'Name'
, max(case when ccp.MetaFieldName = 'MarketAvailabilityDetailsCollection' then ccp.LongString end) as 'MarketAvailability'
, max(case when ccp.MetaFieldName = 'ItemChartCoordinates' then ccp.LongString end) as 'Polygon'
, CoverageNode.Name as Coverage
, RangeNode.Name as 'Range'
FROM dbo.CatalogEntry ce
INNER JOIN dbo.NodeEntryRelation ner ON ce.CatalogEntryId = ner.CatalogEntryId
INNER JOIN dbo.CatalogNode CoverageNode ON dbo.NodeEntryRelation.CatalogNodeId = CoverageNode.CatalogNodeId
INNER JOIN dbo.CatalogNode RangeNode ON CoverageNode.ParentNodeId = RangeNode.CatalogNodeId
INNER JOIN dbo.CatalogContentProperty ccp ON ce.CatalogEntryId = ccp.ObjectId
INNER JOIN dbo.CatalogNode ModelNode ON RangeNode.ParentNodeId = ModelNode.CatalogNodeId
INNER JOIN dbo.CatalogNode BrandNode ON ModelNode.ParentNodeId = BrandNode.CatalogNodeId
WHERE ce.ClassTypeId = N'Variation'
and ccp.MetaFieldName = N'ItemIsChart'
and RangeNode.Name != 'C-MAP'
--and (BrandNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (ModelNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (CoverageNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (RangeNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
and (GEOGRAPHY::STGeomFromText(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STUnion(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STStartPoint()).STAsText(), 4326).STDistance(GEOGRAPHY::STGeomFromText('POINT(50.9835929 -1.4205852)', 4326)) / 1609.344) <= 100 -- OR 'POINT(50.9835929 -1.4205852)' IS NULL -- redundant
)
and max(case when ccp.MetaFieldName = 'MarketAvailabilityDetailsCollection' then ccp.LongString end)
ORDER BY GEOGRAPHY::STGeomFromText(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STUnion(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STStartPoint()).STAsText(), 4326).STArea() DESC;
So the answer is my case was to remove the DISTINCT and to do the duplicate removing using LINQ! Load times went from 10-11ish seconds to 4-5ish seconds

SQL Server 2016 - Stuff/XML Path

I have this basic query, bringing back configuration information. Each MatrixCellID is an individual ticket, and each can have multiple StatisticalGroupCodes and StatisicalGroupDescriptions. Currently each MatrixCellID appears multiple times because of its multiple StatisicalGroupCodes. I would like the Code and Description columns to show all in one column, comma separated.
This is my query:
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
CSG.StatisticalGroupCode,
CSG.StatisticalGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
LEFT JOIN CNF_StatisticalGroup CSG on CSGV.StatisticalGroupId = CSG.StatisticalGroupId
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code
I have tried to use Stuff and XML Path, but cannot get it work correctly with my joins.
Thank you in advance.
You can use this.
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
STUFF(StatGrpCode.StatGroupCodes,1,1,'') StatGroupCodes,
STUFF(StatGrpCodeDesc.StatGroupDescription,1,1,'') StatGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupCode
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCode (StatGroupCodes)
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupDescription
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCodeDesc (StatGroupDescription)
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code

Flag parameter doesn't work correctly (SQL)

I have an "AcctMgr_Flag" that designates a person as the account manager. This is on the table Company_Team. If I send parameter #acctmgr as 'true', I want to return only Activities where #member is the account manager. If #acctmgr is not true, I do not care whether AcctMgr_Flag is true or not.
Every Activity in SO_Activity has an "Assigned_To" column which designates a member_recid. Every Member in Company_Team has an AcctMgr_Flag and Company_RecID. Every Member in v_rpt_Member has a member_recid and a Company_recid.
Here is my code
SELECT v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
FROM v_rpt_Company
LEFT OUTER JOIN SO_Activity
ON v_rpt_Company.Company_RecID = SO_Activity.Company_RecID
LEFT OUTER JOIN v_rpt_Member
ON SO_Activity.Assign_To = v_rpt_Member.Member_ID
LEFT OUTER JOIN Company_Team
ON v_rpt_Member.Member_RecID = Company_Team.Member_RecID AND
v_rpt_Company.Company_RecID = Company_Team.Company_RecID
LEFT OUTER JOIN v_rpt_ActivityType
ON SO_Activity.SO_Activity_Type_RecID=v_rpt_ActivityType.SO_Activity_Type_RecID
LEFT OUTER JOIN v_rpt_ActivityStatus
ON SO_Activity.so_act_status_recid = v_rpt_ActivityStatus.SO_Act_Status_RecID
WHERE (Company_Team.AcctMgr_Flag =
CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END) AND
(SO_Activity.Assign_To = #member) AND
(v_rpt_ActivityStatus.SO_Act_Status_Desc =
CASE WHEN #act_status IS NULL
THEN v_rpt_ActivityStatus.so_act_status_desc ELSE #act_status END) AND
(v_rpt_Company.Company_RecID =
CASE WHEN #company = '' THEN v_rpt_Company.Company_RecID ELSE #company END) AND
(SO_Activity.Last_Update >= CONVERT(datetime, #date_start, 101)) AND
(SO_Activity.Last_Update <= CONVERT(datetime, #date_end, 101))
GROUP BY v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
ORDER BY v_rpt_Company.Company_Name, SO_Activity.Last_Update DESC
Instead of
(Company_Team.AcctMgr_Flag = CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END)
Put this
(#acctmgr != 'true' or Company_Team.AcctMgr_Flag = 1)

Create Clustered/Non Clustered Index in view

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

SQL Set Column Equal to Value

I have the following query. I need Description to be set to the value of the long statement in the middle - the part beginning with CONVERT and ending with [Description]. The query I have now runs but the value of Description in the result is always NULL. Any ideas?
select s.SectionId,
s.Academic_Year [AcademicYear],
s.Academic_Term [AcademicTerm],
s.Academic_Session [AcademicSession],
s.Event_Id [EventId],
s.Event_Sub_Type [EventSubType],
s.Section [Section],
s.Event_Long_Name [EventLongName],
e.Description [EventDescription],
CONVERT(varchar(MAX), S.DESCRIPTION)
+ '<br /><br /><a href="http://www.bkstr.com/webapp/wcs/stores/servlet/booklookServlet?bookstore_id-1=044&term_id-1='
+ CASE S.ACADEMIC_TERM
WHEN 'SPRING' THEN 'SPRING'
WHEN 'SUMMER' THEN 'SUM'
WHEN 'FALL' THEN 'FALL'
WHEN 'J TERM' THEN 'J TERM'
ELSE 'ADV'
END
+ S.ACADEMIC_YEAR + '/' +
CASE S.ACADEMIC_SESSION
WHEN '01' THEN '1'
WHEN '02' THEN '2'
WHEN '03' THEN '3'
END
+ '&div-1=HILB&dept-1=' + SUBSTRING(S.EVENT_ID, 1, CHARINDEX(' ', S.EVENT_ID) - 1) + '&course-1=' + SUBSTRING(S.EVENT_ID, CHARINDEX(' ', S.EVENT_ID) + 1,
LEN(S.EVENT_ID)) + '&section-1=' + CONVERT(varchar(2), S.SECTION) + '" target=' + '"_blank">View Book Information</a>' [Description],
cest.Medium_Desc [SubTypeDescription],
s.Credits [Credits],
cge.Medium_Desc [GeneralEd],
s.Start_Date [StartDate],
s.End_Date [EndDate],
s.Max_Participant [MaximumParticipants],
s.Adds [AddCount],
s.Wait_List [WaitlistCount],
s.Sec_Enroll_Status [EnrollmentStatus],
o.Org_Name_1 [CampusName],
cp.Medium_Desc [ProgramDescription],
cc.Medium_Desc [CollegeDescription],
cd.Medium_Desc [DepartmentDescription],
ccm.Medium_Desc [CurriculumDescription],
ccl.Medium_Desc [ClassLevelDescription],
nt.Nontrad_Med_Name [NonTraditionalDescription],
cpn.Medium_Desc [PopulationDescription],
case s.Other_Org when 'N' then 0 else s.Other_Org_Part end as [CampusOtherLimit],
case s.Other_Program when 'N' then 0 else s.Other_Program_Part end as [ProgramOtherLimit],
case s.Other_College when 'N' then 0 else s.Other_College_Part end as [CollegeOtherLimit],
case s.Other_Department when 'N' then 0 else s.Other_Dept_Part end as [DepartmentOtherLimit],
case s.Other_Curriculum when 'N' then 0 else s.Other_Curric_Part end as [CurriculumOtherLimit],
case s.Other_Class_Level when 'N' then 0 else s.Other_CLevel_Part end as [ClassLevelOtherLimit],
case s.Other_NonTrad when 'N' then 0 else s.Other_NonTrad_Part end as [NonTraditionalOtherLimit],
case s.Other_Population when 'N' then 0 else s.Other_Pop_Part end as [PopulationOtherLimit],
s.Other_Org_Add as [CampusOtherRegistered],
s.Other_Program_Add as [ProgramOtherRegistered],
s.Other_College_Add as [CollegeOtherRegistered],
s.Other_Dept_Add as [DepartmentOtherRegistered],
s.Other_Curr_Add as [CurriculumOtherRegistered],
s.Other_CLevel_Add as [ClassLevelOtherRegistered],
s.Other_Nontrad_Add as [NonTraditionalOtherRegistered],
s.Other_Pop_Add as [PopulationOtherRegistered],
case s.Registration_Type when 'TRAD' then 0 else 1 end as [IsConEd],
cat.Medium_Desc [TermDescription],
cas.Medium_Desc [SessionDescription],
s.Credit_Type [DefaultCreditType],
cct.Medium_Desc [CreditTypeDescription]
from sections s
left join code_eventsubtype cest on cest.code_value_key = s.event_sub_type
left join code_generaled cge on cge.code_value_key = s.general_ed
left join event e on e.event_id = s.event_id
left join organization o on o.org_code_id = s.org_code_id
left join code_program cp on cp.code_value_key = s.program
left join code_college cc on cc.code_value_key = s.college
left join code_department cd on cd.code_value_key = s.department
left join code_curriculum ccm on ccm.code_value_key = s.curriculum
left join code_classlevel ccl on ccl.code_value_key = s.class_level
left join nontraditional nt on nt.nontrad_program = s.nontrad_program
left join code_population cpn on cpn.code_value_key = s.population
left join code_acaterm cat on cat.code_value_key = s.academic_term
left join code_acasession cas on cas.code_value_key = s.academic_session
left join code_acacredittype cct on cct.code_value_key = s.credit_type
One of your inputs must be NULL.
You can probably solve this by identifying which it is and using COALESCE or ISNULL:
COALESCE(x, '')
ISNULL(x, '')
COALESCE is the standard ANSI way, ISNULL gives slightly better performance (although the difference is probably insignificant in most cases).