SQL's stored procedure - sql

Select #vCtlPeriod = period from ctl
IF #vCtlPeriod = #Period
Begin
SET #vHdr = 'StkHdr'
SET #vDtl = 'StkDtl'
End
ELSE
Begin
SET #vHdr = 'HStkHdr'
SET #vDtl = 'HStkDtl'
End
SELECT H.Loc, D.MatCod, D.MatQty, H.Slipno, H.SapWH,
P.InvPri, P.InvPri * D.MatQty as InvAmt, P.ProCat, P.MaiGrp, P.SubGrp1,P.SerCod ,
SUBSTRING(Z.LotNum,1,4) As ProdMth, F.UpdGSPI,
Class = Case WHen F.UpdGSPI = '9' Then 'D'
When Cast(SUBSTRING(Z.LotNum,1,2) AS INT) * 12 + Cast(SUBSTRING(Z.LotNum,3,2) AS INT)>= #vPerClsA Then 'A'
When Cast(SUBSTRING(Z.LotNum,1,2) AS INT) * 12 + Cast(SUBSTRING(Z.LotNum,3,2) AS INT)>= #vPerClsB Then 'B'
When Cast(SUBSTRING(Z.LotNum,1,2) AS INT) * 12 + Cast(SUBSTRING(Z.LotNum,3,2) AS INT)>= #vPerClsC1 Then 'C1'
When Cast(SUBSTRING(Z.LotNum,1,2) AS INT) * 12 + Cast(SUBSTRING(Z.LotNum,3,2) AS INT)>= #vPerClsC2 Then 'C2'
ELSE 'C3'
END,
FGType = Case F.UpdGSPI WHen '1' Then 'Production'
When '2' Then 'Trading'
When '3' Then 'Non GSPI'
When '9' Then 'DisContinue'
Else
'Not Maintain'
End,
FGSTATUS = Case When NOT ISNULL(Z.HolCod,'')='' or NOT ISNULL(Z.ResCod,'')='' Then 'Hold/Reserved'
When NOT ISNULL(Pd.Slipno,'')='' OR NOT ISNULL(Tg.Slipno,'')='' Then 'Pick'
ELSE ''
End,
Tg.SONum , Tg.Seq1, Tg.SptNum, Tg.Qty, Od.LPNum ,
Z.LotNum, Z.DocRefNo, IsNull(Z.HolCod,'') As HolCod, IsNull(Z.HolInf,'') As HolInf, IsNull(Z.ResCod,'') As ResCod, IsNull(Z.ResInf,'') As ResInf
FROM #vHdr H Join #vDtl D ON D.Slipno = H.Slipno And H.Period = #Period
Join Prd P ON D.MatCod = P.ProCod
Join LOCW L ON L.Loc = H.Loc AND L.Pickable <> 'Z' AND L.Putable <> 'Z' AND L.WhCod =H.SapWh
Join ZV00 Z ON Z.SlipNo = H.SlipNo
LEFT JOIN PrdFG F on F.Procod = D.MatCod
LEFT JOIN (SELECT Slipno, MatCod, Qty =Sum(QtyPck) from PickD group by Slipno, matcod) Pd on D.SlipNo = Pd.Slipno and D.MatCod = Pd.MatCod
LEFT JOIN TagLotQty Tg ON TG.SlipNo = D.SlipNo and Tg.procod = D.MatCod
LEFT JOIN OrdD Od ON Od.SONum = Tg.SONum and Od.Seq1 = Tg.Seq1
Above is some of my code in my stored procedure, I intend to check the current period from the ctl file, if the period is current period then I will get from current transaction table or else it will be retrieved from history transaction table.
But I failed at the last select statement. Can we predefined the table name in the variable?

No, we can't. You should use Dynamic SQL or move your SELECT into IF statement

Isn't it simpler to just:
Select #vCtlPeriod = period from ctl
IF #vCtlPeriod = #Period
Begin
SELECt A.*, B.* from StkHdr A Join StkDtl B ON A.Slipno = B.Slipno
End
ELSE
Begin
SELECt A.*, B.* from HStkHdr A Join HStkDtl B ON A.Slipno = B.Slipno
End

You have to use Dynamic SQL like this:
Select #vCtlPeriod = period from ctl
IF #vCtlPeriod = #Period
Begin
SET #vHdr = 'StkHdr'
SET #vDtl = 'StkDtl'
End
ELSE
Begin
SET #vHdr = 'HStkHdr'
SET #vDtl = 'HStkDtl'
End
declare #cmd varchar(500)
select #cmd = "SELECT A.*, B.* from " + #vHDr + " A Join " + #vHdtl + " B ON A.Slipno = B.Slipno "
exec (#cmd)

Related

SQL Query - How to suppress repeating values in the result set?

I'm trying to suppress the repeating values in TotalCarton column. Have tried to replace the value either blank or null but went failed. Any help?
Here is the SQL Script:
SELECT ORDERS.StorerKey,
ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = ( CASE BAX_PACK_DTL.PackType WHEN 'C' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
TotalPallet = ( CASE BAX_PACK_DTL.PackType WHEN 'P' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'C' AND PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'P' AND PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM ORDERS WITH (NOLOCK) INNER JOIN ORDERDETAIL WITH (NOLOCK) ON ORDERS.StorerKey = ORDERDETAIL.StorerKey
AND ORDERS.OrderKey = ORDERDETAIL.OrderKey
INNER JOIN PICKDETAIL WITH (NOLOCK) ON ORDERDETAIL.StorerKey = PICKDETAIL.StorerKey
AND ORDERDETAIL.OrderKey = PICKDETAIL.OrderKey
AND ORDERDETAIL.OrderLineNumber = PICKDETAIL.OrderLineNumber
INNER JOIN BAX_PACK_DTL WITH (NOLOCK) ON PICKDETAIL.OrderKey = BAX_PACK_DTL.OrderKey
AND PICKDETAIL.PickDetailKey = BAX_PACK_DTL.PickDetailKey
WHERE (SELECT COUNT(DISTINCT(ORDERKEY)) FROM PICKDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey ) > 0
AND BAX_PACK_DTL.PackKey = '0000000211'
AND BAX_PACK_DTL.OuterPackID IN
('P111111111',
'P22222222',
'P33333333')
GROUP BY ORDERS.StorerKey,
ORDERS.OrderKey,
ORDERS.ExternOrderKey,
ORDERS.HAWB,
ORDERS.SO,
ORDERS.EditWho,
ORDERS.AddDate,
PICKDETAIL.WaveKey,
BAX_PACK_DTL.OuterPackID,
BAX_PACK_DTL.PackKey,
BAX_PACK_DTL.PackType
ORDER BY BAX_PACK_DTL.OuterPackID ASC
Below is the current result set based on the query above.
Your code looks really strange. I would expect the query to use conditional aggregation and look more like this:
SELECT ORDERS.StorerKey, ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'C' THEN BAX_PACK_DTL.OuterPackID END),
TotalPallet = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'P' THEN BAX_PACK_DTL.OuterPackID END),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'C' AND pbd.PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'P' AND pbd.PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM . . .
GROUP BY ORDERS.StorerKey, ORDERS.OrderKey, Upper(ORDERS.ExternOrderKey),
Upper(ORDERS.EditWho), ORDERS.AddDate;
This may not be exact. You have not qualified column names, given the table structure, and are using very arcane query syntax, mixing subqueries and aggregations. But it should give an idea.

Invalid Object Name - Local SQL Object

The following stored procedure works fine and returns data. However I wanted to also insert the data into a table for debugging before the final select. The code for the insert is commented out just before the final select. The insert uses the exact same select, without the order by, as the data source. However when I run the procedure with the insert uncommented I get an error:
Invalid Object Name BudgetSummaryDetail
I don't why using the object name is fine in the final select but if I try to use it for the insert I get an error. I'm sure there is a reason but I've tried it a bunch of different ways and I can't seem to figure it out. Any help or insight would be most appreciated.
ALTER PROCEDURE [dbo].[rptBudgetSummaryTest]
#Fy AS CHAR(4),
#Index_No AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#PCA AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#Appro_Sym AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#IncludeNonFundedPositions AS BIT = 1,
#OnlyNonZeroPYs AS BIT = 0,
#OnlyNonZeroAllotment AS BIT = 0,
#mrgpcain as dbo.mrgpcain READONLY
AS
IF 1=0 BEGIN
SET FMTONLY OFF
END
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- SET XACT_ABORT ON causes the entire transaction to be
-- rolled back on a run-time error instead of just the sql
-- statement that caused the error.
SET XACT_ABORT ON
BEGIN
-- Tally tables for optional multi-value parameters
SELECT Item
INTO #Index_No_ParamValues
FROM [Common].dbo.Split(#Index_No, ',')
IF (SELECT COUNT(*) FROM #Index_No_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #Index_No_ParamValues
END
SELECT Item
INTO #PCA_ParamValues
FROM [Common].dbo.Split(#PCA, ',')
IF (SELECT COUNT(*) FROM #PCA_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #PCA_ParamValues
END
SELECT Item
INTO #Appro_Sym_ParamValues
FROM [Common].dbo.Split(#Appro_Sym, ',')
IF (SELECT COUNT(*) FROM #Appro_Sym_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #Appro_Sym_ParamValues
END
;WITH
BudgetSummaryDetail
AS (
SELECT
tblPCAIn.FY,
tblPCAIn.Index_No,
tblPCAIn.PCA,
tblPCAIn.Obj_Det,
tblPCAIn.Agy_Obj,
tblPCAIn.PYs,
Calc_PYs = IIF(((tblPCAIn.Obj_Det='427' AND tblPCAIn.Agy_Obj='04') OR tblPCAIn.Obj_Det='439') AND (CAST(tblPCAIn.PCA AS INT) BETWEEN 5000 AND 5999),
IIF(tblPCAFl.Fund_Src = 'F', (tblPCAIn.PYs * tblPCAFl.W_Pnct), 0),
(tblPCAIn.PYs * tblPCAFl.Pnct)),
Calc_Allot = IIF(((tblPCAIn.Obj_Det='427' AND tblPCAIn.Agy_Obj='04') OR tblPCAIn.Obj_Det='439') AND (CAST(tblPCAIn.PCA AS INT) BETWEEN 5000 AND 5999),
IIF(tblPCAFl.Fund_Src = 'F', (tblPCAIn.Allotment * tblPCAFl.W_Pnct), 0),
(tblPCAIn.Allotment * tblPCAFl.Pnct)),
tblPCAFl.Appro_Sym,
tblPCAFl.Fund_Src,
tblPCAFl.Fund_No,
tblPCAFl.Method,
tblPCAFl.Project,
PCT = ROUND(tblPCAFl.Pnct * 100, 0)
FROM
dbo.tblIndex AS tblIndex
INNER JOIN #mrgpcain AS tblPCAIn ON
tblPCAIn.FY = tblIndex.FY AND
tblPCAIn.Index_No = tblIndex.Index_No
INNER JOIN dbo.tblPCA AS tblPCA ON
tblPCA.FY = tblPCAIn.FY AND
tblPCA.PCA = tblPCAIn.PCA
INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
tblPCAFl.FY = tblPCA.FY AND
tblPCAFl.PCA = tblPCA.PCA
INNER JOIN dbo.tblAppro AS tblAppro ON
tblAppro.FY = tblPCAFl.FY AND
tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
LEFT JOIN #Index_No_ParamValues ON
tblIndex.Index_No = #Index_No_ParamValues.Item
LEFT JOIN #PCA_ParamValues ON
tblPCAIn.PCA = #PCA_ParamValues.Item
LEFT JOIN #Appro_Sym_ParamValues ON
tblAppro.Appro_Sym = #Appro_Sym_ParamValues.Item
WHERE
(#Index_No_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #Index_No_ParamValues)) AND
(#PCA_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #PCA_ParamValues)) AND
(#Appro_Sym_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #Appro_Sym_ParamValues)) AND
(((#IncludeNonFundedPositions = 0) AND
(tblPCA.PCA <> '02727')
) OR (#IncludeNonFundedPositions = 1)) AND
(((#OnlyNonZeroPYs = 1) AND
(tblPCAIn.PYs <> 0.0)
) OR (#OnlyNonZeroPYs = 0)) AND
(((#OnlyNonZeroAllotment = 1) AND
(tblPCAIn.Allotment <> 0)
) OR (#OnlyNonZeroAllotment = 0))
)
--DELETE FROM tblBS_Test
--INSERT INTO tblBS_Test
--SELECT * FROM (
--SELECT
-- tblIndex.Dept_Id,
-- tblIndex.Dpty_Id,
-- tblIndex.Brch_Id,
-- tblIndex.Div_Id,
-- detail.Index_No,
-- tblIndex.Index_Title,
-- detail.PCA,
-- tblPCA.PCA_Title,
-- PROGLINK = REPLACE(tblPCA.Program+tblPCA.Element+tblPCA.Component+tblPCA.Task, '', '0'),
-- FUNDLINK = tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
-- tblAppro.Ref,
-- detail.Obj_Det,
-- detail.Agy_Obj,
-- PYs,
-- POS = IIF(((detail.Obj_Det = '003') AND (RTRIM(detail.Agy_Obj) = '')), detail.Calc_PYs, 0.0),
-- Calc_PYs = detail.Calc_PYs,
-- detail.Calc_Allot,
-- PCT
--FROM
-- BudgetSummaryDetail AS detail
-- INNER JOIN dbo.tblIndex AS tblIndex ON
-- tblIndex.FY = detail.FY AND
-- tblIndex.Index_No = detail.Index_No
-- INNER JOIN dbo.tblPCA AS tblPCA ON
-- tblPCA.FY = detail.FY AND
-- tblPCA.PCA = detail.PCA
-- INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
-- tblPCAFl.FY = tblPCA.FY AND
-- tblPCAFl.PCA = tblPCA.PCA AND
-- tblPCAFl.Appro_Sym = detail.Appro_Sym AND
-- tblPCAFl.Fund_Src = detail.Fund_Src AND
-- tblPCAFl.Fund_No = detail.Fund_No AND
-- tblPCAFl.Method = detail.Method AND
-- tblPCAFl.Project = detail.Project
-- INNER JOIN dbo.tblAppro AS tblAppro ON
-- tblAppro.FY = tblPCAFl.FY AND
-- tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
-- INNER JOIN dbo.tblAgyDE AS tblAgyDE ON
-- tblAgyDE.Obj_Det = detail.Obj_Det AND
-- tblAgyDE.Agy_Obj = detail.Agy_Obj
-- INNER JOIN dbo.tblObjDe AS tblObjDe ON
-- tblObjDe.Obj_Det = tblAgyDE.Obj_Det
-- INNER JOIN dbo.tblCat AS tblCat ON
-- tblCat.Category = tblObjDe.Category) as myda
SELECT
tblIndex.Dept_Id,
tblIndex.Dpty_Id,
tblIndex.Brch_Id,
tblIndex.Div_Id,
detail.Index_No,
tblIndex.Index_Title,
detail.PCA,
tblPCA.PCA_Title,
PROGLINK = REPLACE(tblPCA.Program+tblPCA.Element+tblPCA.Component+tblPCA.Task, '', '0'),
FUNDLINK = tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
tblAppro.Ref,
detail.Obj_Det,
detail.Agy_Obj,
PYs,
POS = IIF(((detail.Obj_Det = '003') AND (RTRIM(detail.Agy_Obj) = '')), detail.Calc_PYs, 0.0),
Calc_PYs = detail.Calc_PYs,
detail.Calc_Allot,
PCT
FROM
BudgetSummaryDetail AS detail
INNER JOIN dbo.tblIndex AS tblIndex ON
tblIndex.FY = detail.FY AND
tblIndex.Index_No = detail.Index_No
INNER JOIN dbo.tblPCA AS tblPCA ON
tblPCA.FY = detail.FY AND
tblPCA.PCA = detail.PCA
INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
tblPCAFl.FY = tblPCA.FY AND
tblPCAFl.PCA = tblPCA.PCA AND
tblPCAFl.Appro_Sym = detail.Appro_Sym AND
tblPCAFl.Fund_Src = detail.Fund_Src AND
tblPCAFl.Fund_No = detail.Fund_No AND
tblPCAFl.Method = detail.Method AND
tblPCAFl.Project = detail.Project
INNER JOIN dbo.tblAppro AS tblAppro ON
tblAppro.FY = tblPCAFl.FY AND
tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
INNER JOIN dbo.tblAgyDE AS tblAgyDE ON
tblAgyDE.Obj_Det = detail.Obj_Det AND
tblAgyDE.Agy_Obj = detail.Agy_Obj
INNER JOIN dbo.tblObjDe AS tblObjDe ON
tblObjDe.Obj_Det = tblAgyDE.Obj_Det
INNER JOIN dbo.tblCat AS tblCat ON
tblCat.Category = tblObjDe.Category
ORDER BY
tblIndex.Dept_Id,
tblIndex.Dpty_Id,
tblIndex.Brch_Id,
tblIndex.Div_Id,
detail.Index_No,
detail.PCA,
tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
detail.Obj_Det,
detail.Agy_Obj
IF Object_id('tempdb..#Index_No_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #Index_No_ParamValues;
END
IF Object_id('tempdb..#PCA_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #PCA_ParamValues;
END
IF Object_id('tempdb..#Appro_Sym_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #Appro_Sym_ParamValues;
END
RETURN 0
END
GO

Performance Issue in Select groupby

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

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

Conversion failed when converting the varchar value '*' to data type int

I'm getting this issue when i'm running nested while loops in sql server 2005.
My outer loop gets one iteration, and then my inner loop gets it's full first iteration, but my statement after the inner loop never gets executed, which then seems to break everything.
I'm lost right now and I feel like I'm missing something very easy, any help is much appreciated.
while exists(select top 1 ident from #tmpAttorneyImport (nolock) where parsed = 0 and zipcode <> '')
begin
set #intCurrentIdent = 0
set #vcrCurrentAttonreyName = ''
set #vcrCurrentZip = ''
select top 1 #intCurrentIdent = ident from #tmpAttorneyImport (nolock) where parsed = 0
select #vcrCurrentAttonreyName = ltrim(rtrim(attorneyname)) from #tmpAttorneyImport (nolock) where ident = #intCurrentIdent
select #vcrCurrentZip = ltrim(rtrim(zipcode)) from #tmpAttorneyImport (nolock) where ident = #intCurrentIdent
if(len(#vcrCurrentZip) > 3)
begin
set #vcrMinZip = ''
set #vcrMaxZip = ''
select #vcrMinZip = ltrim(rtrim(left(#vcrCurrentZip, 3)))
select #vcrMaxZip = ltrim(rtrim(right(#vcrCurrentZip, 3)))
while(convert(int, #vcrMinZip) <= convert(int, #vcrMaxZip)) -- sql is telling me this line has the error
begin
insert into #tmpAttorneysFormatted(
attorneyname,
zipcode
)
select
attorneyname = #vcrCurrentAttonreyName,
zipcode = case
when len(#vcrMinZip) = 1 then '00' + ltrim(rtrim(#vcrMinZip))
when len(#vcrMinZip) = 2 then '0' + ltrim(rtrim(#vcrMinZip))
when len(#vcrMinZip) = 3 then ltrim(rtrim(#vcrMinZip))
end
select #vcrMinZip = convert(int, #vcrMinZip) + 1
end
-- this statement does not get hit
update #tmpAttorneyImport
set
parsed = 1
where
ident = #intCurrentIdent
end
else
begin
insert into #tmpAttorneysFormatted(
attorneyname,
zipcode
)
select
attorneyname = #vcrCurrentAttonreyName,
zipcode = case
when len(#vcrCurrentZip) = 1 then '00' + ltrim(rtrim(#vcrCurrentZip))
when len(#vcrCurrentZip) = 2 then '0' + ltrim(rtrim(#vcrCurrentZip))
when len(#vcrCurrentZip) = 3 then ltrim(rtrim(#vcrCurrentZip))
end
update #tmpAttorneyImport
set
parsed = 1
where
ident = #intCurrentIdent
end
end
select #vcrMinZip = ltrim(rtrim(left(#vcrCurrentZip, 3)))
select #vcrMaxZip = ltrim(rtrim(right(#vcrCurrentZip, 3)))
How sure are you that your data is clean?
I'd put in (right after this) two lines:
print #vcrMinZip
print #vcrMaxZip
and see what is actually being parsed out of the string.